How to Change Background Color of Selected Text in HTML and CSS

In this tutorial, we will learn how to change background color of selected text in HTML and CSS.  When you are creating a website, you may want to change the selected text background color for a decent user interface and user experience.

In the majority of browsers, the chosen text background color is blue by default.  The default background color of a selected text can be changed easily by using CSS ::selection pseudo-element.

In the following example, we have 2 elements and we will change their default selected text background color.  Please have a look over the code example and the steps given below.

HTML

  • In the HTML file, we have 2 elements (h1 and p).
  • The h1 element and p element contain some text content.
  • In the head element, we have added a stylesheet (style.css) using the link element.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selected text background color change</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <h1>selected text background color change</h1>
    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Error minima at ipsam porro ab consequatur, hic eius architecto? Laborum nihil similique veniam consequatur! Sequi officia sapiente mollitia, eveniet dolores praesentium, incidunt fugiat expedita modi itaque cumque corporis quia! Laboriosam nulla ratione ab vitae atque praesentium, veniam adipisci modi? Totam, ratione.</p>
</body>

</html>

CSS

  • We are selecting the h1 element with CSS ::selection pseudo-element and setting the background property to green and color property to yellow.  As a result, when the user selects the text, the default background and text color will change to green and yellow respectively.
  • Similarly, we are selecting the p element with CSS ::selection pseudo-element and setting the background property to red and color property to white.  As a result, when the user selects the text, the default background and text color will change to red and white respectively.
h1::selection {
    background: green;
    color: yellow;

}

p::selection {
    background: red;
    color: white;

}