If you’ve seen websites display different foreground or background colours on highlighted text and wonder how they do it, it’s actually very simple.

Once part of the draft CSS Selectors Level 3 specification, the ::selection pseudo-element allows you to specify a different text highlight colour than the default the browser applies when a user highlights text on a Web page. Here’s an example:

p::selection {
color: #777777;
background-color: #f5f5f5;
}

p::-moz-selection {
color: #777777;
background-color: #f5f5f5;
}

Essentially, the CSS code above instructs the browser to render the text in any paragraph tag with the foreground and background colours we’ve specified.

As mentioned, the ::selection pseudo-element is (unfortunately) not a part of any official W3C specification (it was, but it was later removed for reasons unknown), so if you care about or need to keep your stylesheets valid in the eyes of the W3C CSS Validator, you will need to avoid using this pseudo-element entirely.

Firefox Caveat

Firefox observes standards much more strictly than some other browsers, and does not implement the ::selection pseudo-element itself, since it is not officially part of the CSS Level 3 spec. This is a good thing because it means if ::selection is standardised in the future, Firefox is really the only browser that would be able to implement ::selection correctly if specific technical standards changed that affected developers using it (unlikely, but possible).

Thankfully, Firefox has their own proprietary property that you can use instead, as shown above.

Browser Support

::selection – IE 9 and above, Chrome 4 and above, Safari 3.1 and above, Opera 10.1 and above, Android Browser 4.4 and above, Opera Mobile 12 and above, Chrome for Android 40 and above, IE Mobile 10 and above

::-moz-selection – Firefox 2 and above, Firefox for Android 33 and above

(Subject to change at any time – the listed browsers may or may not support it in future versions)

Note: It is not recommended to rely on CSS features that are not standardised, because there is a greater risk a Web browser may remove support for an unofficial CSS selector or pseudo-element at any time without notice. Therefore, consider them strictly as a non-essential extra to your visitors’ overall experience and be prepared for it to “break” at any time.

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *