Logo

dev-resources.site

for different kinds of informations.

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

Published at
6/30/2021
Categories
css
pseudoelements
Author
evelew
Categories
2 categories in total
css
open
pseudoelements
open
Author
6 person written this
evelew
open
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.


Featured ones: