How to change the color of selected text using CSS?

To change the color of selected text using CSS, you can use the ::selection pseudo-element. This feature allows you to customize the appearance of text when users select it with their mouse or keyboard.

Syntax

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

/* Or target specific elements */
element::selection {
    color: value;
    background-color: value;
}

Supported Properties

The ::selection pseudo-element only supports a limited set of CSS properties

Property Description
color Text color of selected content
background-color Background color of selected content
text-shadow Shadow effect on selected text
cursor Cursor type (limited support)

Example 1: Global Text Selection

This example applies the same selection style to all text on the page

<!DOCTYPE html>
<html>
<head>
<style>
    ::selection {
        color: white;
        background-color: #04af2f;
    }
</style>
</head>
<body>
    <h3>Changing the Color of Selected Text Using CSS</h3>
    <p>
        In this example we have used <strong>::selection</strong>
        pseudo-element to change the color of selected text using CSS.
    </p>
    <div>
        Select any text to see the green background and white text color.
    </div>
</body>
</html>
When you select any text on the page, it will appear with white text on a green background (#04af2f).

Example 2: Element-Specific Selection Styles

This example applies different selection styles to specific elements

<!DOCTYPE html>
<html>
<head>
<style>
    div::selection {
        color: white;
        background-color: #04af2f;
    }
    section::selection {
        color: white;
        background-color: #16031f;
    }
    article::selection {
        color: #f35b31;
        background-color: #eeb1fa;
    }
</style>
</head>
<body>
    <h3>Element-Specific Selection Colors</h3>
    <div>
        Select this div text to see green background with white text.
    </div>
    <section>
        Select this section text to see dark purple background with white text.
    </section>
    <article>
        Select this article text to see pink background with orange text.
    </article>
</body>
</html>
Each element displays different selection colors: div shows green background with white text, section shows dark purple background with white text, and article shows pink background with orange text.

Browser Support

The ::selection pseudo-element is supported in all modern browsers. For older Firefox versions, use ::-moz-selection as a fallback.

Conclusion

The ::selection pseudo-element provides an easy way to customize text selection appearance. You can apply it globally or target specific elements for more precise control over your website's user experience.

Updated on: 2026-03-15T16:18:14+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements