How to Set a Custom Text-Selection Color with CSS



Here’s a cool trick that can be used as a nice finishing touch on any website or project. If you’re meticulous about your branding and design and want every single aspect of your site to reflect that, or even if you’re just looking for a fun way to add some extra color to your site, this tutorial is for you

By using CSS’s ::selection pseudo-selector, you can actually override the browser’s (or the user’s, if they have it set on their machine) default text-selection color. The new text-selection color (you know, the color that highlights the text or elements when you select them) can be any color of your choosing. Take a look at the code below to see how it’s done.

::selection{
    background: #f98295;
}

That’s literally it. Adding the one line of CSS above to your stylesheets is all it takes to turn your text-selection color into a nice watermelon pink. Changing the selection color really couldn’t be easier. The example above will apply the effect to ALL HTML elements, but if you want it to only apply to <p> tags, for example, you can do so by placing a p in front of the pseudo-selector, like this:

p::selection{
    background: #f98295;
}

This pseudo-selector isn’t universally supported by all browsers, so it’s a good idea to use your usual vendor prefixes along with it if you’re adding it to any of your projects.

Leave a reply
this will never be published
@