DEV Community

Cover image for CSS Text Transform: You Don't Need JavaScript to Capitalize Your Text
Niall Maher
Niall Maher

Posted on • Originally published at codu.co

CSS Text Transform: You Don't Need JavaScript to Capitalize Your Text

Sometimes we over-engineer things...

In this previous article I showed you how to capitalize a string with JavaScript.

Here's a snippet from it:

let str = "hello world";
let capitalizedStr = str.slice(0, 1).toUpperCase() + str.slice(1);
console.log(capitalizedStr); // "Hello world"
Enter fullscreen mode Exit fullscreen mode

This might be useful in some cases, but if you are doing it to display a value, there is an easier way.

CSS Text Transform Property

The CSS text-transform property is used to specify text capitalization in an element. This property can be applied to any text-containing element, like paragraphs, headings, lists, etc. The text-transform property accepts the following values:

  • none - Leaves the value unchanged
  • capitalize - Capitalize the value
  • uppercase - Uppercase the value
  • lowercase - Lowercase the value

So to capitalize our paragraphs, it would be as simple as applying the following in our CSS:

p {
  text-transform: capitalize;
}
Enter fullscreen mode Exit fullscreen mode

The CSS text-transform property is a powerful tool for manipulating text styles on a web page, making them convenient to know. 🦾


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers?
You can join our free web developer community here. 🎉

Top comments (3)

Collapse
 
ant_f_dev profile image
Anthony Fung

This is definitely useful to know and caught me out once.

I was working in a project that used icon fonts, where certain words resulted in different icons being displayed. The wrong icon was being shown and I couldn't understand why - I could see the correct text being used in the browser developer tools.

It turned out that the text was lower case, but being transformed to upper case by CSS. This caused the icon for the upper case version of the text to be shown.

Collapse
 
nialljoemaher profile image
Niall Maher

Oooh I'd love to see that use case because that would be a great gotchya to teach people too.

Collapse
 
ant_f_dev profile image
Anthony Fung

I was working on an inhouse solution at the time. The team had created a font where the characters were icons, so we could use that (with fully scalable vector-based icons) instead of having to rely on fixed-size raster images. Think something like font-awesome.

Unfortunately, I don't think I'm allowed to say more than that.