CSS: Target the First Letter of Every Word

Is there any way with CSS you can target the first letter of every word?

I know you can use:

  • text-transform:uppercase to make the first letter of every word capital.
  • font-variant: small-caps to create small caps
  • ::first-letter to target the first letter of an element (but not the first letter of every word in that element)

However, is there anything that lets you target the first letter of every word. I thought the CSS3 selectors would allow for something, but I haven’t been able to find it.

Thanks for any help

You can use this to capitalize the first letter of each word:

.selector { text-transform: capitalize; }

Or is that not what you are looking for?

Thanks for replying!

No, I don’t want to capitalize the first letter. I actually want to re-size first the first letter.

(Sorry, in my opening post I meant to put text-transform: capitalize in the first bullet (instead of uppercase)).

With CSS that is not possible, not even with CSS3.

The easiest option would be to wrap the first letter of each word in a <span>. Another option would be to try a javascript solution.

Yes, CSS is no help here. Welcome to the world of JavaScript, where anything is possible.


window.onload = function(){
  var elements = document.getElementsByClassName("each-word")
  for (var i=0; i<elements.length; i++){
    elements[i].innerHTML = elements[i].innerHTML.replace(/\\b([a-z])([a-z]+)?\\b/gim, "<span class='first-letter'>$1</span>$2")
  }
}


<style>
  .first-letter {
    color: red;
  }
</style>
<p class="each-word">First letter of every word is now red!</p>

Thanks! That worked perfectly. Thank you very much for your kindness and help. Thanks!

Sorry to bump up an old thread, but I have a follow up question and I thought it would be politer to continue this thread than to start a new one.

The code lpcstr posted works perfectly. Except, if there is any HTML inside the “each-word” element (for example, an anchor or a span tag), the HTML gets converted into regular text.

Is there away around this?

Thanks for any help!