How to change the selection color when the user selects content using a mouse pointer or cursor in CSS?

Published August 6, 2021

To change the color of the selection area when the user selects some content, you can use the ::selection pseudo-element and write the CSS styles to be applied inside the block in the CSS stylesheet.

TL;DR

/* Change color of selection when 
   user selects the content */
::selection {
  background-color: blue;
  color: white;
}

For example, suppose we have a HTML structure showing some content like this,

<!-- Simple HTML structure -->
<html>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

Normally, in most browsers when the user selects the content Hello World with the mouse pointer or the cursor, they will see a blueish background color to indicate that the text has been selected. This color depends on the browser and varies on different browsers.

Normally it may look like this,

To change this color, we can use the ::selection pseudo-element in the CSS stylesheet like this,

::selection {
  /* Your CSS styles to apply when 
    user selects content in the HTML */
}

Let's say we want to change the background color of the selection to blue and the color of the text to white when the user selects the content using his mouse pointer or cursor.

So to do that we can define those CSS styles to be applied inside the ::selection block like this,

::selection {
  /* Your CSS styles to apply when 
    user selects content in the HTML */
  background-color: blue;
  color: white;
}

It may look like this,

Yay 🎉! We have successfully changed the colors when the user selects the content.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter