How to change text selection highlight color using CSS
When you select some text on a web page by pressing and holding the left mouse key and dragging the mouse over the text, the background, and color of the selected text change from that of other text.
If you try selecting text on different websites, you are likely to notice (or have already) that the highlight background and text color may vary from one site to another.
This highlight color can differ due to:
- The default highlight color of the user's operating system.
- Customization by the developer.
The default highlight color of the user's operating system
Each operating system has its own default text highlight color. When you select the same text on the same web page across different operating systems, you will notice that the highlight color may differ.
I took the screenshot below on a page from this website using the Firefox browser on Ubuntu 20.04.
I took the screenshot below from the same web page as the above using the Firefox browser on Windows 10.
Customization by the developer
As a website developer, you have control over the look and feel of your website. You can choose which colors you want to highlight texts on your website using CSS styling.
How to preferred text highlight color with CSS
To set the text selection/highlight color, we use the CSS
The following CSS properties can be applied to ::selection:
You can customize all the above properties on your webpage selection using
::selection as in the examples below:
<title>Setting text highlight color</title>
<p>This is a sample paragraph. Select it to highlight!</p>
<div>This is a div element</div>
Below is the screenshot of the above page with the paragraph highlighted with green background color and yellow text color.
In case you want the highlight color to only apply to specific page elements eg. a div, a paragraph, etc, you just add the CSS selector of that element before
You can as well use the Id or Class of the element with the
From the example above, the text within an element with the id 'paragraph1' will have a yellow color and green background on selection. The text within an element with class 'paragraph2' will have a white color and orange background on selection.
Selecting some text on a web page makes the selected text have a different color and background color. These colors may differ depending on the operating system you use and as a result of the customization by the developer.
The developer can easily customize the highlight/selection background and text colors through the use of CSS
::selection pseudo-element with the