How to Change Selected Text Color in HTML and CSS

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

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

In the following example, we have 2 elements and we will change their default selected text 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 both have 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 color change</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <h1>selected text 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 color property to green.  As a result, when the user selects the text, the default selected text color will be green.
  • Similarly, we are selecting the p element with CSS ::selection pseudo-element and setting the color property to red.  As a result, when the user selects the text, the default selected text color will be red.
h1::selection {
    color: green;
}

p::selection {

    color: red;
}