Open In App

How to Change Selected Text Background Color in CSS?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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 GeeksforGeeks, A 
        computer science portal
    </p>
</body>

</html>

Output:

selected-text-background-color

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>GeeksforGeeks</h1>

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

</html>

Output:

selected-text-background-color-2


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads