CSS Custom Highlight API example

CSS Custom Highlight API example. Paint a Range with HighlightRegistry and ::highlight(). No extra DOM spans.

The problem

In some cases, you want to highlight text in a document without modifying the DOM structure. Traditional methods, such as wrapping text in <mark> tags, can lead to issues with layout and accessibility. The CSS Custom Highlight API provides a way to create custom highlights that can bed with CSS without altering the underlying HTML.

The method

With the CSS Custom Highlight API, you can create a Highlight object that groups multiple Range objects. You can then register this highlight with a name using CSS.highlights.set(), and it using the ::highlight() pseudo-element in your CSS. This allows for flexible and efficient text highlighting while keeping the DOM intact.

new Range()

Walks the text nodes in the stage. One range per hit. Does not paint. Does not wrap.

const range = new Range()
range.setStart(textNode, start)
range.setEnd(textNode, end)

new Highlight()

A set of ranges. One highlight, many hits, one. Still not paint. The name comes later.

const highlight = new Highlight(...ranges)
highlight.size

CSS.highlights.set()

Registers the highlight as lab-hits. ::highlight(lab-hits) is the paint. Same nodes. No mark.

CSS.highlights.set("lab-hits", highlight)

CSS.highlights.clear()

Drops every custom highlight in this document. The ranges still exist. The paint does not.

CSS.highlights.clear()

All Web API labs

  • CSS overflow carousel example
  • CSS Anchor Positioning example
  • Customizable select example