CSS HTML

How to change the color of selected text with CSS (fast and easy)

October 21, 2021

How to change the color of selected text with CSS (fast and easy)

In this article we will see how to change the color of selected text with CSS, in a practical way without external libraries.

change the color of selected text with CSS cover

Before starting, you’ve probably come across the default style of selected text from HTML, right?

If not, see how it looks:

Of course it depends on operating system and browser, but at least on Linux/Ubuntu, it’s like this

In the Windows, it turns out to that big blue screen! haha

Also, I’m going to present the HTML code that we’re going to use during this example, you can copy it from here:

<!DOCTYPE html>
<html>
 <head>
  <title>Texto selecionado</title>
 </head>
 <body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum, nulla vel dictum aliquam, odio purus maximus urna, eget facilisis lorem risus vel nulla. Quisque vehicula mauris sit amet nisl dictum egestas. Duis tincidunt odio id erat malesuada commodo. Integer non nibh sed dolor ultrices iaculis. Pellentesque ligula quam, ornare ut faucibus vitae, elementum nec velit. Curabitur nec fringilla odio. Sed pharetra dolor non ex pharetra, et iaculis ex fringilla. Aliquam interdum ultrices nisi, a bibendum mi facilisis ac. Suspendisse potenti.</p>
 </body>
</html>

With the HTML structured and already delivered to you, now let’s make the necessary additions to change the color of the selected text with CSS

Changing the color of selected text applying CSS in practice

To perform this action, we just need to add the pseudo element ::selection, to the desired element

See the example:

p::selection {
 color: lightblue;
 background-color: black;
}

In this case, we’ll add it to our HTML paragraph and we’ll change the color of the text and its background

Now see the final result:

Isn’t that simple?

Learn more about pseudo elements too, they shorten the code lines in web development, some of them are:

  • ::after
  • ::before
  • ::cue
  • ::first-letter
  • ::first-line
  • ::selection
  • ::slotted

Conclusion

In this article we saw that it is very easy to change the color or style of the selected text.

With the ::selection pseudo-element on the desired element, we can create a rule and change the style of the selection

And that’s it for today; see you in the next post!

Want to learn more about CSS? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x