How to change selected text background color in CSS
The default text selection color is white with a blue background but if we don't want use the default style of selected text then we can use this CSS property ::selection to change the selection color of text and also it's background. Let's try it how?
The below text 1 is without CSS ::selection property and text 2 is with ::selection property, try to select the text 1 and 2 you will see the difference.
Text 1: Without ::selection property
This is a paragraph Line.
Text 2: With ::selection property
This is a paragraph Line.
How it works?
To do that you will need to write some HTML code before applying the ::selection property. Understand it with example below:
Input
<p>This is a paragraph Line.</p>
<h1> This is Paragraph 2 </h1>
<p id="text2">This is a paragraph Line.</p>
<style>
/* Use identifier to specify selection */
#text2::selection {
color: white;
background: #e24ca8;
}
</style>
Output
This is Paragraph 1
This is a paragraph Line.
This is Paragraph 2
This is a paragraph Line.
In above output you will see effect to the last line as I have used id="text2" in <p> tag to specify the selection of a particular paragraph. However, you can use ::selection property without specifying a identifier. You can do that for your complete web. Let's try it too!
Input
<p>This is a paragraph Line.</p>
<h1> This is Paragraph 2 </h1>
<p >This is a paragraph Line.</p>
<style>
/* using ::selection property without identifier*/
::selection {
color: white;
background: #e24ca8;
}
</style>
Output
This is Paragraph 1
This is a paragraph Line.
This is Paragraph 2
This is a paragraph Line.
Now select the above output, the ::selection property will show it's full impact on complete paragraph. This is because we just use the ::selection property but didn't specify it with a identifier. So, it is effecting the whole paragraph. Moreover, identifier can be anything i.e. class, id, or any other HTML tag.