How to change the color of selected text using CSS ?

The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on <h1> and <p> element and set its colour as yellow with green background.

Below example implements the above approach:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
        How to change the color of
        selected text using CSS?
    </title>
      
    <style>
        .geeks h1 {
            color: green;
        }
          
        h1::selection {
            background: green;
            color: yellow;
        }
          
        p::selection {
            background: green;
            color: yellow;
        }
    </style>
</head>
  
<body>
    <div class="geeks">
        <h1>GeeksforGeeks</h1>
          
        <p>
            A Computer Science portal for
            geeks. It contains well written,
            well thought and well explained
            computer science and programming
            articles, quizzes and many more.
        </p>
    </div>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.