DEV Community

Cover image for Use a pseudo-element from CSS instead of toUpperCase method from JS
Evellyn Lima
Evellyn Lima

Posted on

Use a pseudo-element from CSS instead of toUpperCase method from JS

It's common to find a toUpperCase() method inside a JS file to transform a text into uppercase, sometimes this method is used to uppercase only the first letter from a sentence.

Does it work? Yes. Does is it the ideal? I believe it doesn't. In these cases, we are using JS to control some parts of our layout, and with this in mind, we should prioritize the use of CSS.

And, not by chance, only with CSS we can set the first letter to uppercase.
To solve this we need to use the ::first-letter pseud-element.

Let's use this HTML as example:

<p class="message">evellyn, your address was updated.</p>
Enter fullscreen mode Exit fullscreen mode

We have a paragraph with the class message with the text "evellyn, your address was updated.", the ideal is my name appears with the first letter as uppercase. Using CSS we can make it this way:

.message::first-letter {
  text-transform: uppercase;
}
Enter fullscreen mode Exit fullscreen mode

With it, we change the style only to the first letter from the selector message, now our sentence will appear as it should: "Evellyn, your address was updated."


JS allows us to make a lot of things, but sometimes it is not the right choice. It's always important to search how we can make that UI change using only CSS.


Top comments (2)

Collapse
 
maxart2501 profile image
Massimo Artizzu

If you want to capitalize every word in an element instead, text-transform: capitalize is your friend.

I always suggest to use CSS to transform to uppercase. It usually is meant to be a presentational transformation after all, so CSS is the right place to perform it when possible.

Collapse
 
evelew profile image
Evellyn Lima

Yep, I agree.