Styles of text selection
Some of you may notice that text selections in this blog are not default. I mean if you select some text its background is not blue. I believe that it is OK to change some defaults to make the design of your website more consistent. CSS can help you with that.
Disclaimer: People expect some defaults by… default. And the selection is one of such things. Don’t change the default behavior just because you can. The selection should be obvious.
If the default blue background for the selection on your website is not compatible with the design of your website, you can use
::selection pseudo-element to change it.
For ancient Firefox versions (61 and below) don’t forget about
::selection pseudo can change not all the CSS properties inside of it. The list is really short:
If you use SVG, you can also change
This restriction can be simply explained. When the user selects the text, they expect to have an immediate response. And, of course, there should not be any layout shifts. Any background images can cause an image loading, and any margins will cause layout shifts. So, you can change only fast for rendering properties. And when you use
background: blue, the browser will change it to
It’s important to remember accessibility. The contrast ratio between the background color and text color must be at least
4.5:1. Don’t forget about the contrast between selection background and element background. If they have almost the same color, your users will be confused.
By default, browsers try to use system settings for selection. For example, macOS users can change the selection color via “OS Settings → General” and Chrome respects this color. There is no way to get this color from JS or CSS (it will be a big privacy issue if they can).
There is another selection that Blink browsers have by default. Try to visit this link. If you use Chromium-based browser you will see the selection on a text fragment passed to the URL. And you can style this selection too.
::target-text has the same restrictions as
::selection. MDN proposes to change
font-weight in their example, but I hope this PR will be merged soon.