Search code examples
csscapitalize

Why Css text-transform capitalize not working?


I have an example text and it all Uppercase. I want to make it capitalized text, but css text-transform doesn't work. How can i do this?

span,
a,
h2 {
  text-transform: capitalize !important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<span class="ml-5 mt-5 d-block">IT IS AN EXAMPLE TEXT</span>

<h2><a class="ml-5 mt-5 d-block" href="#">IT IS AN EXAMPLE TEXT IN HREF</a></h2>

And you can check in JSFiddle

I want first letter Upper, others lower for all words. Like this:

It Is An Example Text

Solution

  • CSS text-transform: capitalize will only affect the first character.

    According to the specs:

    capitalize Puts the first character of each word in uppercase; other characters are unaffected.

    I strongly suggest to just have the content edited. Remember that at the end of the day, technologies such as css is just 1 way to solve the problem. The better solution, again, would be to edit that content and capitalize it, whether it be stored in the database or just static content in the markup.


    As a hack (if you really want to use a code-level solution), you can use JavaScript to transform all letters first into lowercase. Then use /\b(\w)/g to match the instances of first letters, then use toUpperCase() on each

    document.querySelector("a").innerText = document.querySelector("a").innerText.toLowerCase().replace(/\b(\w)/g, x => x.toUpperCase());
    <h2><a class="ml-5 mt-5 d-block" href="#">IT IS AN EXAMPLE TEXT IN HREF</a></h2>