How to use ::selection Pseudo-element In CSS

The ::selection pseudo-element is used to style the background color of the selected text. This pseudo-element targets the portion of a text that is currently selected by the user.

Syntax:

::selection {
    background-color: color_name;
    color: color_name;
}

Example 1: In this example, we will change the selected text color and background color using CSS.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        How to Change Selected Text 
        Background Color in CSS?
    </title>
    
    <style>
        ::selection {
            background-color: green;
            color: white;
        }
    </style>
</head>

<body>
    <p>
        Welcome to w3wiki, A 
        computer science portal
    </p>
</body>

</html>

Output:

Example 2: In this example, we will change the selected text color and background color based on element in CSS.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        How to Change Selected Text 
        Background Color in CSS?
    </title>
    
    <style>
        body {
            text-align: center;
        }
        
        h1::selection {
            background-color: green;
            color: white;
        }

        p::selection {
            background-color: blue;
            color: red;
        }
    </style>
</head>

<body>
    <h1>w3wiki</h1>

    <p>
        Welcome to w3wiki, A 
        computer science portal
    </p>
</body>

</html>

Output:


How to Change Selected Text Background Color in CSS?

Sometimes, we need to change the color and background color of the selected text. The ::selection pseudo-element is used to change the background color of the selected text in CSS. This pseudo-element allows you to style the portion of text that has been selected by the user.

Similar Reads

Using ::selection Pseudo-element

The ::selection pseudo-element is used to style the background color of the selected text. This pseudo-element targets the portion of a text that is currently selected by the user....