ado.xyz
Blog Courses About

How to Change the Highlight Color of an HTML Document

April 27, 2020

Highlighting HTML pages typically produces a highlight consisting of a blue background with white text, but did you know you can easily change this behavior with CSS?

There’s plenty of good reasons why you would want to do this. For example, say you have a hero element that has a blue background and white text already, the highlighted text wouldn’t even show up. Another reason might be just to have a consistent experience with the rest of your website.

::selection CSS element

To change the look and feel of highlighted text on an HTML page you will use the ::selection operator. You can apply this operator as wide or as narrow as you see fit. Let’s take a look at a few examples.

Change the Highlight Color For Your Entire Page

To change the highlight color for your entire document, meaning apply your changes globally, simply apply the ::selection pseudo-tag by itself or on the body tag.

::selection {
  /* Change highlight background color to black */
  background: #000;
  /* Change highlight text color to red */
  color: #ff0000;
}

Narrow the ::selection Scope

As with all things CSS, we can easily scope down the use of this element. So let’s say we just wanted to change the background color of our <p> tags. We would do it like this:

p::selection {
  /* Change highlight background color to black */
  background: #000;
  /* Change highlight text color to red */
  color: #ff0000;
}

Now our paragraphs would have a dark background with red text, but the rest of the DOM elements would use the default blue background on white text.

::selection Example

Here’s an example where we’ll scope it down to a specific class. Feel free to highlight the underlying paragraph to see the changes.

p.byte-ex-1::selection {
  background: #333;
  color: cyan;
}

Highlight me to see the above effect applied.

The ::selection pseudo-element makes it easy to change the highlighted background as well as the color of the text. There are additional configurable properties defined in the spec such as allowing you to set the text-decoration and cursor properties but these are not widely supported in browsers as of April, 2020.

Newsletter

Subscribe to the newsletter and be the first to know when I publish new content. No Spam.