Using the selection selector to change the default highlight color
What is the selection pseudo selector?
You can target this pseudo element to change the highlight color of selected text within the element.
What can i use the selection pseudo selector for?
You can target this selector and change the properties to effect the look and background colour, and the foreground text colour as well.
Preview of the selection pseudo selector
How to use title
To target the elements with css, you can just add the :: and then the selector name. ::selection
. If i had an element called my-element then i would target it with .my-element::selection{}
and then in the brackets i would then change the attribites.
Update: the rainbow background selection does not work, apparently linear gradient backgrounds are not supported on the selection element. there maybe a way around this, but i have not found one as yet.
Using the selection selector to change the default highlight color Demo
View Demo Full Screen View Demo New Tab
Using the selection selector to change the default highlight color Code
HTML
<div class="box-wrap">
<div>
<p>
If you highlight this text you can see the default highlight colour.
</p>
<p class="pink-highlight">
If you select this text it should be Pink!
</p>
<p class="rainbow-highlight">
This is the best one, a rainbow gradient highlight! Hightlight me...
</p>
</div>
</div>
CSS
.box-wrap {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
p {
font-size: 2rem;
font-family: sans-serif;
}
.pink-highlight::selection {
background-color: pink;
color: #fff;
}
.rainbow-highlight::selection {
background-color: linear-gradient(45deg, #dc3b3e, #3b99dc 50%, #3bdc90 75%, rgb(255 141 0) 100%);
}