Something cool that you can do using just CSS is change the selection color when you are range selecting content.
Normally, the selection color is whatever your browser default is:
[ yaaaaawn... ]
By using the selection CSS pseudo-element, you can easily define a different highlight background color as well as the color of the text being highlighted:
[ you can see a live example here ]
In this short article, you will learn how to use the selection pseudo-element to create your own highlight color different from what the browser creates.
First, create a new HTML page and paste the following code:
If you preview this page in its current state and select some text, all you will see is what you saw in the first image towards the top of this page. The selection color is your browser/OS default. Let's fix it so that you get the page to look more like the second one with a custom selection color!
To change the selection color, you will need to use the selection pseudo-element. Go ahead and paste the following CSS rules below your mainContent rule:
If you preview your page now and highlight the text, you will see the selection with a pink background and a white foreground color. Wohoo!
Let's look at the CSS you pasted in greater detail. The first half of the selector is pretty straightforward. I am specifying that the rule applies to p tags that live inside an element whose id is mainContent:
The selection pseudo-element goes after your selector:
This pseudo-element marks this entire style rule as being related to the selection of content. When it comes to modifying your selection, you can only specify the background color of the selected content and the foreground color of the selected content.. You can't change anything else during your selection.
As you can imagine, this greatly limits the number of CSS properties you can use:
You can use the background or background-color property to specify the background color of your selection, and you can use the color property to specify the color of the highlighted text.
Once you have made those changes, your selection background and foreground color will look custom and unique to your design.
Changing the selection color of your content is pretty easy. The selection pseudo-element was originally a part of the W3C spec, but it has been removed recently. Despite its removal from the spec, all of the browser vendors support it, so you should feel free to use it. Thanks to @krilnon for linking to the MDN docs that clarified the selection pseudo-element's future.