How to Change Selected Text Background Color in CSS

In this tutorial, you will learn how to change selected text background color in CSS. Whenever you select a text in your browser to copy or just for highlighting purpose, you must have noticed that it always gives you default blue color in the background. To change this color, you can make use of ::selection pseudo element.
 
::selection pseudo element can be used to apply any set of CSS props to the highlighted portion of the document. It is widely supported by all modern browsers, but there are few older browsers which do not support it such as IE6-8, Opera mini etc. You can get complete list of supported browsers here. HTML, CSS and Javascript code is given below.
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <h1>This is H1 Element</h1>
    <p>This is paragraph Element</p>
    <div>This is DIV Element</div>
    
</body>
</html>

 

CSS:

body {
    display: flex;
    flex-direction: column;
    align-items: center;
}

h1, p, div {
    border: 1px solid black;
    padding: 10px;
}
/* 
p::selection {
    background-color: black;
    color: #fff;
}

div::selection {
    background-color: yellow;
    color: red;
} */

::selection {
    background-color: yellow;
    color: red;
}

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •