7
votes

Is it possible to capitalize the first letter only of a word that is all caps using CSS?

So change "TESTING" to "Testing"?

<span class = "capitalize">TESTING</span>

The css property text-transform: capitalize doesn't work (capitalizes the first letter but ignores the rest).

6

6 Answers

11
votes

Yes it is possible with just CSS, here's how:

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

.capitalize:first-letter {
  text-transform: uppercase
}
<span class = "capitalize">TESTING</span>

You'll notice I added display:inline-block, this is because:

"A first line has meaning only in a block-container box, therefore the ::first-letter pseudo-element has an effect only on elements with a display value of block, inline-block, table-cell, list-item or table-caption." source

3
votes

CSS:

<style>
    p.capitaliseFirstLetterOnly {
        text-transform: lowercase;
    }
    p.capitaliseFirstLetterOnly::first-letter{
        text-transform: uppercase;
    }
</style>

HTML:

<p class="capitaliseFirstLetterOnly">TESTING.</p>
1
votes

You can use jquery as follows:

<span class="capitalize">MYTEXT</span>
    <script>
        $(document).ready(function () {
            var txt = $(".capitalize").text().toLowerCase();
            txt = txt.toLowerCase().replace(/\b[a-z]/g, function (letter) {
                return letter.toUpperCase();
            });
            $(".capitalize").text(txt); 
        });        
    </script>

Reference:

Uppercase first letter of variable

0
votes
0
votes
.capitalize::first-letter {
     text-transform: capitalize;
}

https://jsfiddle.net/5wbe2ugq/

There's no way to see in CSS if the first letter is capitalized, however you can make sure of it via:

.capitalize::first-letter {
     text-transform: capitalize;
}

.capitalize {
     text-transform: lowercase;
}
0
votes
 <style>
.capitalize{
  text-transform:lowercase;
  display: inline-block;
}
.capitalize::first-letter {
     text-transform:capitalize; 
}
</style>
<span class = "capitalize">TESTING</span>

Make sure to add display:inline-block because the element span does not work with :first-letter unlike with p,div,tables, etc. If you are using an element which has block by default, then you don't need to put a display:inline-block just like the code below.

 <style>
.capitalize{
  text-transform:lowercase; 
}
.capitalize::first-letter {
     text-transform:capitalize; 
}
</style>
<div class = "capitalize">TESTING</div>

Cheers,