Changing the text selection color with CSS

โœ๏ธ

Did you know you can change the selection color in CSS?

5 Nov, 2020 ยท 2 min read

Did you know a CSS property can change the user selection behavior?

It got some excellent support lately and is one of these cool gimmicks. It doesn't break anything for the browser that doesn't support it.

The result will look like this.

CSS Selection selector

HTML Structure

For our demo, we will have multiple paragraphs that each do something different.

<div>
  <h3>Select this paragraph in yellow marker</h3>
  <p class="yellow">Content here</p>
</div>

<div>
  <h3>Select this paragraph in black/white</h3>
  <p class="black">Content here</p>
</div>

<div>
  <h3>Select this paragraph in shadow text</h3>
  <p class="shadow">Content here</p>
</div>

CSS Selection selector

Now we are going to use the selection attribute selector.

The default selector is written like this:

::selection {
  color: red;
}

Then we can add a Mozilla specific one:

::-moz-selection {
  color: red;
}

For our instance let's start with the yellow marker one:

p.yellow::selection {
  background: #ffff00;
}
p.yellow::-moz-selection {
  background: #ffff00;
}

This will make the background of the selection a yellow color.

Now if we move on to our black and white selector:

p.black::selection {
  background: #000;
  color: #fff;
}
p.black::-moz-selection {
  background: #000;
  color: #fff;
}

This will make the background black and the text color white.

Lastly, I wanted to show you can do more than primary color selection and even add a text shadow!

p.shadow::selection {
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
}
p.shadow::-moz-selection {
  text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
}

Have a play around on this Codepen.

See the Pen Changing the text selection color with CSS by Chris Bongers (@rebelchris) on CodePen.

Browser Support

The browser support for the ::selection has improved lately and can be used safely.

CSS selection support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Bringing perspective to CSS

7 Aug, 2022 ยท 2 min read

Bringing perspective to CSS

Creating a 3D Cylinder shape in CSS

29 Jul, 2022 ยท 3 min read

Creating a 3D Cylinder shape in CSS