Simon Blackbourn

Styling selected text with CSS

Sometimes it's the little touches that make a design feel truly finished, that make visitors to your website feel that you've paid attention to every last detail. Styling selected text with CSS is one of those things.

By default, most browsers highlight selected text with a blue background, which very often clashes with the other colours used on the website. Here's a screenshot from my own company website:

Screenshot of a website showing some highlighted text with the default blue background

The ::selection pseudo-element

Using the ::selection pseudo-element in CSS allows us to target selected text. Most commonly, I change the background colour and font colour, but you could change the case, font weight, etc. Personally, I prefer to keep it simple and not overdo things.

::selection {
    background-color: #f7d500;

Here's the result, showing the selected text now matching the primary branding colour:

Screenshot of a website showing highlighted text styled using CSS with a background colour that matches the primary branding colour

See it in action

Select any text here on this website, or on my company website as shown in the example above, to see this in action.

Browser support

Browser support for the ::selection pseudo-element is extremely good (even IE9 supports it), with Safari on iOS being the only major exception. This doesn't matter however, as the rule is ignored by any browser that doesn't understand it.