The CSS Custom Highlight API is a draft W3C specification for styling arbitrary text ranges from JavaScript, and it is being positioned as the future of text-range styling on the web. Styling ranges matters in everyday software: text editors like Google Docs, Word, and Dropbox Paper draw squiggly underlines under spelling and grammar errors, code editors like VS Code flag code errors the same way, and browser find-in-page highlights search matches. Browsers handle these cases internally (<textarea> spelling squiggles, the find command), but doing the same thing yourself on a web page has long been a costly problem.

Why text highlighting is hard on the web

The task is not as simple as wrapping text in a <span> with a class and applying CSS. A correct implementation must highlight multiple ranges across an arbitrarily complex DOM tree, potentially crossing element boundaries. Two approaches are common today: style-able text range pseudo-elements, and a homegrown highlighting system.

Approach 1: style-able text ranges

The best-known style-able range is the user selection. Selecting text with a pointing device creates a Selection object — document.getSelection() in DevTools shows location information for the selected text.

DevTools window showing the position of the current selection in the console.

A selection can also be created programmatically from JavaScript:

// First, create a Range object.
const range = new Range();

// And set its start and end positions.
range.setStart(parentNode, startOffset);
range.setEnd(parentNode, endOffset);

// Then, set the current selection to this range.
document.getSelection().removeAllRanges();
document.getSelection().addRange(range);

The range is then styled with the ::selection pseudo-element, which is supported across all browsers:

::selection {
  background-color: #f06;
  color: white;
}

Related pseudo-elements exist for other browser-predefined ranges: ::target-text for text scrolled to via scroll-to-text in supporting browsers, ::spelling-error for text the browser flags as a spelling error, and ::grammar-error for grammar errors. Browser support for these is not great, and none of them can style custom pieces of text — only browser-predefined ones.

The selection technique is attractive because it is relatively simple to put in place and does not change the page's DOM: Range objects are essentially coordinates of segments in the page rather than HTML elements that must exist. Its major drawback is that creating a selection resets whatever the user has already selected manually; any selection the code moves elsewhere wipes the user's own.

Approach 2: build your own highlighting system

If the Selection object is insufficient, the remaining option is to do everything yourself: use JavaScript to insert new HTML elements into the DOM wherever highlighting should appear. That means far more JavaScript to write and maintain, and it forces the browser to re-create the page layout whenever highlighting changes. Edge cases are complicated too, such as a highlight spanning multiple DOM elements.

Illustration showing a line of HTML with an emphasis element and a strong element with a bright yellow highlight running through them.

CodeMirror and Monaco (the editor library behind VS Code) take a slightly different tack with their own highlighting logic: highlights live in a separate part of the DOM tree, with lines of text and highlighted segments rendered in two different places and positioned over each other. Inspecting the DOM subtree that holds the text reveals no highlights, so highlights can be re-rendered without touching the lines of text or introducing elements inside them. What has been missing is a browser-powered highlighting feature that avoids all these drawbacks — no interference with user selection, multi-selection support, simple code — and runs faster than custom solutions.

The API, step by step

The CSS Custom Highlight API (currently a Working Draft) lets developers create arbitrary ranges from JavaScript and then style them with CSS, much like the selection technique. Using it takes four steps.

1. Create the ranges

Ranges are created with the JavaScript Range object, as when setting a selection:

const range = new Range();
range.setStart(parentNode, startOffset);
range.setEnd(parentNode, endOffset);

Note that setStart and setEnd behave differently depending on the first argument: for text nodes the offset is a character count within the node, and for other nodes it is a count of child nodes within the parent. These two methods are not the only way to describe a range's start and end; the Range class offers other methods.

2. Create Highlight objects

A Highlight object takes one or more Ranges. To style several pieces of text identically, create a single Highlight holding all their ranges:

const highlight = new Highlight(range1, range2, ..., rangeN);

You can also create as many Highlight objects as needed — for instance, a collaborative editor where each user gets a different text color can use one Highlight per user, each styled differently.

3. Register the highlights

A Highlight does nothing until it is registered in the highlight registry via the CSS Highlights API. The registry behaves like a map where highlights are registered under names, removed, or cleared entirely:

CSS.highlights.set('my-custom-highlight', highlight);

Here my-custom-highlight is a name of your choosing and highlight is the Highlight object from the previous step.

4. Style the highlights

The new ::highlight() pseudo-element styles a registered highlight by the name given at registration:

::highlight(my-custom-highlight) {
  background-color: yellow;
  color: black;
}

As with ::selection, only a subset of CSS properties applies to ::highlight(): background-color, caret-color, color, cursor, fill, stroke, stroke-width, text-decoration (likely supported only in version 2 of the specification), and text-shadow.

Updating registered highlights

Highlighted text can be changed in several ways without rebuilding objects:

  • Clear the whole registry with CSS.highlights.clear() and start over.
  • Update the underlying ranges with range.setStart and range.setEnd (or any other Range methods); the browser repaints the highlights.
  • Mutate a Highlight, which behaves like a JavaScript Set: highlight.add(newRange) adds a range and highlight.delete(existingRange) removes one.
  • Add or remove Highlight objects from the CSS.highlights registry, which behaves like a JavaScript Map, using set and delete.

Browser support

Implementation is still incomplete, so the API is not ready for production. The Microsoft Edge team is implementing it in Chromium, and it can be used today in Canary builds by enabling the Experimental Web Platform features flag under about:flags. No firm ship date exists for Chrome, Edge, and other Chromium-based browsers, but support is close. Safari 99+ supports the API behind an experimental flag (Develop → Experimental Features → Highlight API), with a slightly different interface that uses StaticRange objects instead. Firefox does not support it yet; Mozilla's position is documented on GitHub.

Microsoft Edge also provides a demo of the API highlighting text ranges in a page based on what you type in a search field. Before trying it, use Chrome or Edge Canary with the Experimental Web Platform features flag set in about:flags. After the page loads, JavaScript retrieves all text nodes using a TreeWalker; as the user types, the code iterates over those nodes until it finds matches, creates Range objects from them, and highlights them with the Custom Highlight API.

Why it is worth it

The four-step flow — ranges, then highlights, then registration, then styling — may look complicated at first, but it is far simpler than creating and inserting new DOM elements in the right places. More importantly, browser engines can style these ranges very, very fast. The restricted property subset exists precisely because those properties can be applied effectively without recreating the page layout, whereas inserting DOM elements around text forces the engine to do much more work. Fernando Fiori, who worked on the API, built a performance comparison demo; on the source author's machine, the CSS Custom Highlight API ran on average 5× as fast as DOM-based highlighting. With experimental support in Chromium and Safari, production use is getting close.