Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-elements

The ::highlight() pseudo-element

Reference for the CSS ::highlight() pseudo-element: style text ranges registered with the CSS Custom Highlight API, such as search matches, without extra markup.

The ::highlight() pseudo-element styles custom highlights: ranges of text that JavaScript registers with the CSS Custom Highlight API. It lets you mark search matches, spell-check results or collaborative selections without wrapping text in <mark> or <span> elements, so the DOM stays unchanged.

Two parts work together. JavaScript creates Range objects, puts them in a Highlight and registers it under a name with CSS.highlights.set(name, highlight). CSS then styles that name with ::highlight(name).

CSS
::highlight(search) {
  background: gold;
}

Try it

Highlighting search matches

Syntax

CSS
::highlight(<custom-ident>) {
  /* a limited set of properties */
}
Property Value
Applies to Text covered by the registered ranges
Inherited Inherits from the element that contains the text
Animatable No

Values

Part Description
<custom-ident> The name used in CSS.highlights.set().
color, background-color Text and fill color of the highlighted range.
text-decoration and related Underlines and line-through.
text-shadow Shadow behind the text.

Properties that change layout (such as font-size, margin or padding) are not allowed, as with ::selection.

Usage notes

  • Priority. Each Highlight has a priority number; the higher one wins when ranges overlap.
  • Ranges follow the DOM. If the text node changes, ranges may collapse or move. Recompute the ranges after edits.
  • Highlights are not accessible by themselves. Assistive technology does not learn about them. Do not rely on color alone to convey meaning.
  • Not in the DOM. Ctrl+F, copying and text extraction are unaffected, which is the main advantage over wrapping text.
  • Feature-detect. Test CSS.highlights before using it, as the example does.
  • One name, many ranges. A highlight can hold many ranges, even across elements.
  • Stacking with selection. The user's real selection is drawn above custom highlights.

Browser support

The Custom Highlight API is supported in current Chrome, Edge, Safari and Firefox. Older versions, particularly of Firefox, lack it, so feature-detect and provide a fallback such as <mark>.