DEV Community

Cover image for How to change the selection color when the user selects content using a mouse pointer or cursor in CSS?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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;
}
Enter fullscreen mode Exit fullscreen mode

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

<!-- Simple HTML structure -->
<html>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

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,

blueish selection color when user selects content

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 */
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

It may look like this,

custom CSS styles colors when user selects content

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 😃.


Top comments (0)