πŸ’‘ This page contain affiliate links. By making a purchase through them, we may earn a commission at no extra cost to you.
Change the Color of a Selected Text in CSS with One Rule

Change the Color of a Selected Text in CSS with One Rule

Ferenc Almasi β€’ 2022 June 27 β€’ Read time 1 min read
  • twitter
  • facebook
CSS

You can change the color and background of your text selection in CSS with the pseudo ::selection selector.

Copied to clipboard!
::selection {
  background: black;
  color: white;
}

This will change both the color and the background color of your text selection globally. You can also attach the selector to an element to target specific elements on the page. For example, take a look at the following code and the effect they produce below.

Copied to clipboard! Playground
.left::selection {
    background: black;
    color: yellow;
}

.right::selection {
    text-shadow: 1px 1px 5px #fff;
}

Try to select me to see selection styles applied!

Try to select me to see selection styles applied!

Only certain CSS properties can be used with the ::selection selector.

You can use color, background, and text-shadow. Other rules are ignored. It is supported by all major browsers. Currently, it is only unsupported on iOS Safari, Opera Mini, and older versions of IE and Android Browser. For unsupported browsers, the rule is ignored without causing any issues. For the full list of support tables, check out caniuse.com

  • twitter
  • facebook
CSS
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.