The ::selection-pseudo-element
Published on
I recently put up a quiz on YouTube asking about pseudo-elements, and it turns out that ::selection
isn’t as well known as I’d thought, with 24% of respondents (out of over 9,000) saying it isn’t a valid pseudo-element.
While you might not need it for every project, it allows you to change the color of selected text on pages away from the default blue.
::selection {
background: red;
color: white;
}
You can select this text to see it in action (though it won’t work on iOS…).
You can apply it site-wide using ::selection
like I did above, but you can also scope it to specific elements using a selector along with it:
::selection {
background: hsl(0 0% 8%);
color: hsl(0 0% 90%);
}
.dark-component::selection {
background: hsl(0 0% 90%);
color: hsl(0 0% 8%);
}
If you are going to change the color of your selection, just make sure that the selected text has good contrast, making it easy to read.
You can only style a limited set of properties
While it would be cool if we could create gradients of our selections with this, the only properties that we can style using ::selection
are:
color
background-color
text-decoration
text-shadow
- and the
-webkit-
prefixed properties for stroke and fill.
Dive deeper
- MDN
::selection
article - A YouTube Short exploring
::selection
- Selection Styling - Chrome for Developers Blog that goes into how inheritance works with it, including many examples