The ::highlight() pseudo-element styles a named set of text ranges registered through the CSS Custom Highlight API. CSS does not find the ranges: JavaScript creates Range objects, constructs a Highlight, and registers its name. The paint is limited to supported highlight properties and does not insert a mark element or create semantic emphasis.
CSS ::highlight(): paint searched text without changing its markup
When to use it
A policy viewer marks current search matches as the user edits a query. The application updates the registered ranges; CSS gives them a pale background and dark foreground so the text remains legible. Provide a separate result count and keyboard path to each match. If a passage is important editorially even when search is idle, use semantic markup rather than a transient highlight registry. Test overlapping ranges, selection across a match, a query with no results, and a browser without the API. The search result list should still work when the paint is unavailable. Do not attach actions or tooltips to a highlight as though it were a DOM element. Keep its color distinct from text selection, and check that forced colors or user themes do not remove the only visible indication of the active match.
::highlight(policy-search-match) { color: #163441; background-color: #ffe28a; }
@media (forced-colors: active) { ::highlight(policy-search-match) { color: HighlightText; background-color: Highlight; } }Cost and verification
Highlighting a very large number of ranges can increase style and paint work; update only the needed ranges when a query changes and measure a long document. The API setup and search algorithm are separate from the CSS sample. A range can become stale after the text nodes change, so the application must rebuild it after content replacement. The registry name in CSS must match the JavaScript registration name. A fallback result list is necessary because this paint has no semantics and may be unsupported. Avoid promising that the effect can decorate an arbitrary box: it paints text ranges under the API's property restrictions.
Common Mistakes
- Do not expect CSS to discover or register search ranges.
- Do not treat a custom highlight as semantic mark text.
- Do not make the highlight color the only way to locate a result.
