# ::highlight()

> The `::highlight()` CSS pseudo-element styles text ranges registered with the CSS Custom Highlight API.

## How do I highlight text ranges without wrapping them in spans?

The pseudo-element that applies styles to ranges of text registered in `CSS.highlights` from JS. Used for search results, syntax highlighting or spell checking without wrapping text in extra elements.

- Topic: Pseudo Elements
- Type: pseudo-element
- Browser support: Chrome 105+, Chrome Android 105+, Edge 105+, Firefox 149+, Firefox Android 149+, Safari 17.2+, Safari iOS 17.2+

## Example

Wrong:

```js
const html = p.innerHTML;
p.innerHTML = html.replaceAll(term, `<mark>${term}</mark>`);
```

Right:

```js
const range = new Range();
range.setStart(textNode, start);
range.setEnd(textNode, start + term.length);
CSS.highlights.set('search', new Highlight(range));
```

Highlights paint ranges without changing the DOM, so no HTML is rebuilt and injection through `innerHTML` is avoided.

## Common mistakes

- Nothing shows because the name in `CSS.highlights` differs from the one in `::highlight()`.

## Key points

- Ranges are registered with `CSS.highlights.set(name, new Highlight(range))`, and the name matches `::highlight(name)`.
- Only text styles like `color`, `background-color` and `text-decoration` are used; others are ignored.
- Highlights aren't exposed to screen readers, so important states are also conveyed another way.

## Interview questions

### Can a highlight span multiple elements?

Yes. A `Range` can start and end in different text nodes, and the highlight paints across them.

### How do I remove a custom highlight?

Call `CSS.highlights.delete('search')` to remove one, or `CSS.highlights.clear()` to remove all of them.

## Related cards

- [::selection](https://wonderium.dev/css/selection.md)
- [::target-text](https://wonderium.dev/css/target-text.md)
- [`<mark>`](https://wonderium.dev/html/mark.md)
- [Pseudo-element](https://wonderium.dev/css/pseudo-element.md)
- [text-decoration](https://wonderium.dev/css/text-decoration.md)

---

- Level: [CSS](https://wonderium.dev/css.md)
- HTML version: https://wonderium.dev/css/highlight
- Last updated: 2026-11-25
