CSS custom highlight API

The CSS custom highlight API module provides a programmatic way to target specific ranges of text defined by range objects, without affecting the underlying DOM structure. The range objects can then be selected via ::highlight() pseudo-elements, and have highlight styles added and removed. The features of this module can create highlight effects similar to how text editors highlight spelling or grammar errors, and code editors highlight syntax errors.

The CSS Custom Highlight API extends the concept of other highlight pseudo-elements such as ::selection, ::spelling-error, ::grammar-error, and ::target-text by providing a way to create arbitrary text ranges (defined as Range objects in JavaScript) and style them via CSS, rather than being limited to browser-defined ranges.

Custom highlight API in action

To enable styling text ranges on a webpage using the CSS Custom Highlight API, you create a Range object, then a Highlight object for the range. After registering the highlight using the HighlightRegistry.set() method, you can then select the range using the ::highlight() pseudo-element. The name defined in the set() method is used as the parameter of the ::highlight() pseudo-element selector to select that range.The range selected by the ::highlight() pseudo-element can be styled using a limited number of properties.

This example uses the text-decoration property to strike throgh the steps highlight range defined by our JavaScript:

css
::highlight(steps) {
  text-decoration: line-through;
  color: blue;
}

We create a Range with a start and end node (which is the same node in this case). We then set this range as the Highlight using the set() method of the CSS HighlightRegistry interface.

js
const rangeToHighlight = new Range();
const list = document.querySelector("ol");
rangeToHighlight.setStart(list, 0);
rangeToHighlight.setEnd(list, 0);
CSS.highlights.set("steps", new Highlight(rangeToHighlight));

An event listener updates the end of the highlighted range when the number of completed steps changes:

js
const currentPositionSlider = document.querySelector("input");
currentPositionSlider.addEventListener("change", (e) => {
  rangeToHighlight.setEnd(list, e.target.value);
});

Reference

Pseudo-elements

Interfaces

Interface extensions

This module adds properties and methods to interfaces defined in other specifications.

Guides

CSS custom highlight API

The concepts and usage of the CSS custom highlight API, including creating Range and Highlight objects, registering the highlights using the HighlightRegistry, and styling the highlights using the ::highlight() pseudo-element.

Specifications

Specification
CSS Custom Highlight API Module Level 1

See also