Override the Default Text Selection Background Color Using CSS

In this article, well use the ::selection
CSS declaration to change the background color of the text that is highlighted by a user of your website.
The ::selection
CSS pseudo element that adds styles to a part of your HTML that has been highlighted by the user (this includes clicking and/or dragging their mouse across text). Not all browsers will support it, but it wont hurt anything since the non-compatible browsers will just ignore it.
For more information on browser compatibility for the ::selection
declaration, check out this Mozilla documents page.
Here is the CSS code to make the magic happen:
::selection {
background: rgb(244, 63, 75);
}
::-moz-selection { /* Mozilla Firefox browser compatibility */
background: rgb(244, 63, 75);
}
The code above will apply the selection background color to all the HTML elements in its jurisdiction.
But you can also apply the ::selection
to specific elements, classes, or IDs:
/* Apply to an element id */
#element-id::selection {
background: #800080;
}
#element-id::-moz-selection {
background: #800080;
}
/* Apply to an element class */
.element-class::selection {
background: #800080;
}
.element-class::-moz-selection {
background: #800080;
}
/* Apply to an element */
span::selection {
background: #800080;
}
span::-moz-selection {
background: #800080;
}
There you have it! Go build something cool!
Thanks for reading and happy coding!