CSS Change text Selection Color of HTML Elements

How to change the text selection color using CSS?

The ::selection selector of CSS

There is a selector in CSS called ::selection which is used to change the text selection colors of HTML elements.

The following code will change the text selection color of all elements.

<style>
    ::selection{
        background-color: brown;
        color: white;
        
    }
</style>

<h1>Lorem, ipsum dolor.</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, deserunt.</p>
CSS change HTML text selection color of all elements
Result

Change text selection color of specific elements

You can also specify text selection color for specific elements.

selector::selection{
    /* background-color:...;
       color:...; */
}

The following code will apply the text selection color only to the <p> elements.

<style>
    p::selection{
        background-color: brown;
        color: white;
        
    }
</style>

<h1>Lorem, ipsum dolor.</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iste, deserunt.</p>
CSS change HTML text selection color of specific elements
Result