CSS custom highlight API
TheCSS 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 asRange objects in JavaScript) and style them via CSS, rather than being limited to browser-defined ranges.
In this article
Custom highlight API in action
To enable styling text ranges on a webpage using the CSS Custom Highlight API, you create aRange object, then aHighlight object for the range. After registering the highlight using theHighlightRegistry.set() method, you can then select the range using the::highlight() pseudo-element. The name defined in theset() 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 alimited number of properties.
<h1>Directions</h1><h2>Lincoln Memorial to Martin Luther King, Jr. Memorial</h2><ol><li>Head south on Lincoln Memorial Circle</li ><li>Turn right toward Independence Ave</li ><li>Turn left onto Independence Ave</li ><li>Turn right onto West Basin Dr</li ><li>Look up when you reach 64 Independence Ave!</li></ol><hr /><label >Number of steps completed: <input type="number" min="0" max="5" value="0" /></label>This example uses thetext-decoration property to strike through thesteps highlight range defined by our #"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:
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
RangeandHighlightobjects, registering the highlights using theHighlightRegistry, and styling the highlights using the::highlight()pseudo-element.
Related concepts
::grammar-error::selection::spelling-error::target-textRangeInterface andRange()constructor- Text fragments
FragmentDirectiveInterface
Specifications
| Specification |
|---|
| CSS Custom Highlight API Module Level 1> |