CSS text-transform capitalize on all caps

Here is my HTML:

<a href="#" class="link">small caps</a> & 
<a href="#" class="link">ALL CAPS</a>

Here is my CSS:

.link {text-transform: capitalize;}

The output is:

Small Caps & ALL CAPS

and I want the output to be:

Small Caps & All Caps

Any ideas?


You can almost do it with:

.link {
  text-transform: lowercase;
}
.link:first-letter,
.link:first-line {
  text-transform: uppercase;
}

It will give you the output:

Small Caps
All Caps

There is no way to do this with CSS, you could use PHP or Javascript for this.

PHP example:

$text = "ALL CAPS";
$text = ucwords(strtolower($text)); // All Caps

jQuery example (it's a plugin now!):

// Uppercase every first letter of a word
jQuery.fn.ucwords = function() {
  return this.each(function(){
    var val = $(this).text(), newVal = '';
    val = val.split(' ');

    for(var c=0; c < val.length; c++) {
      newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
    }
    $(this).text(newVal);
  });
}

$('a.link').ucwords();​

Convert with JavaScript using .toLowerCase() and capitalize would do the rest.


Interesting question!

capitalize transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. Not even the :first-letter pseudo-class will cut it (because it applies to the first letter of each element, not each word), and I can't see a way of combining lowercase and capitalize to get the desired outcome.

So as far as I can see, this is indeed impossible to do with CSS.

@Harmen shows good-looking PHP and jQuery workarounds in his answer.


I'd like to sugest a pure CSS solution that is more useful than the first letter solution presented but is also very similar.

.link {
  text-transform: lowercase;
display: inline-block;
}

.link::first-line {
  text-transform: capitalize;
}
<div class="link">HELLO WORLD!</div>
<p class="link">HELLO WORLD!</p>
<a href="#" class="link">HELLO WORLD!  ( now working! )</a>

Although this is limited to the first line it may be useful for more use cases than the first letter solution since it applies capitalization to the whole line and not only the first word. (all words in the first line) In the OP's specific case this could have solved it.

Notes: As mentioned in the first letter solution comments, the order of the CSS rules is important! Also note that I changed the <a> tag for a <div> tag because for some reason the pseudo-element ::first-line doesn't work with <a> tags natively but either <div> or <p> are fine. EDIT: the <a> element will work if display: inline-block; is added to the .link class. Thanks to Dave Land for spotting that!

New Note: if the text wraps it will loose the capitalization because it is now in fact on the second line (first line is still ok).