CSS ::Selection Selector with Example
The ::selection selector in CSS is a pseudo-element that selects a portion of the document selected or highlighted by the user in the browser using mouse or any other pointing device.
Generally, it will occur when a user drags their mouse over text, or taps on a touch screen. By default, most browsers highlight selected text with a blue background color, but you can change this style with the ::selection selector.
With ::selection selector, you can use only some CSS properties, such as color, background, text-decoration, text-shadow, outline, and cursor to customize the appearance of selected text.
Basic Syntax to Use CSS ::selection Selector
The general syntax to use the ::selection selector in CSS is as follows:
::selection {
property: value;
}
Example of ::selection Selector
Here’s a simple example in which the selector ::selection will apply the yellow background color and black text color of selected text in the browser.
Example 1:
<!DOCTYPE html>
<html>
<head>
<style>
::selection {
background-color: yellow;
color: black;
}
</style>
</head>
<body>
<h2>Select this text to see the effect!</h2>
<p>This is a very simple example of using the::selection selector in CSS.</p>
</body>
</html>
Output:
As you can see in this output, we have selected some text that is appearing in a yellow background and black text.
Customizing Selection for Different Themes
Let’s take an example in which we will customize the text selection style based on the theme of your website. For instance, you can use different styles for light and dark themes.
Example 2:
<!DOCTYPE html>
<html>
<head>
<style>
/* Light Theme */
body.light-theme ::selection {
background-color: #007bff;
color: white;
}
/* Dark Theme */
body.dark-theme ::selection {
background-color: #ffcc00;
color: black;
}
</style>
</head>
<body class="light-theme"> <!-- Change to 'dark-theme' for dark mode -->
<h2>Select this text to see the effect on the webpage!</h2>
<p>The appearance of selected text will change based on the theme.</p>
</body>
</html>
When browser render this code, the selected text on the light-theme mode will appear in blue background color and white text color. If the theme is on the dark mode, the selected text will appear in yellow background color and black text.
In this tutorial, you have learned about the CSS ::selection selector that provides a unique style to enhance the user experience by customizing text selection styles. As mentioned above, only very few CSS properties you can apply to ::selection selector. If you will try to use properties like border, margin, or padding will have no effect.
Most modern browsers, such as Google Chrome, Firefox, etc. support the ::selection pseudo-element. However, there may be differences in how browsers rendered it.