Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

::highlight() — styling custom text highlights

The ::highlight() pseudo-element styles text ranges registered through the CSS Custom Highlight API without adding wrapper elements. CSS defines the appearance, while JavaScript creates the ranges and registers the highlight under a name.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

::highlight(<custom-ident>)
/* Editor’s Draft: */
::highlight(<highlight-name-selector>)
/* <highlight-name-selector> = '*' | <custom-ident> */

::highlight() names a functional pseudo-element; it is not a valid selector with an empty argument. It represents text portions covered by a custom highlight. Unlike ::selection, it does not require the user to select text. Ranges can cross element boundaries without changing the DOM structure.

The notations ::highlight(<custom-highlight-name>) and ::highlight(<custom-ident>) describe selecting a highlight by name; angle brackets indicate placeholders, not literal code. In ::highlight(demo), the argument demo corresponds to the key in CSS.highlights.set('demo', ...). CSS alone does not create a range: JavaScript passes a Range to Highlight and registers the object in CSS.highlights.

The Editor’s Draft extends the syntax to ::highlight(<highlight-name-selector>), accepting either <custom-ident> or *. ::highlight(*) selects all custom highlights, but not built-in highlights such as ::selection. The named form contributes specificity (0,0,1), while the * form contributes (0,0,0). This draft extension requires separate verification in the target browser.

Only properties allowed for highlights apply, including color and background-color; margin, display, and font-size cannot change their layout. The example covers the range from index 6 to exclusive index 10, namely Beta. Checking API availability and selector syntax does not prove correct rendering; the appearance must also be checked.

Examples

<!doctype html>
<meta charset="utf-8">
<title>Custom highlight</title>
<style>
  ::highlight(demo) {
    color: #000000;
    background-color: #ffff00;
  }
</style>
<p id="text">Alpha Beta Gamma</p>
<pre id="status"></pre>
<script>
  const status = document.getElementById('status');
  if (!('Highlight' in window) || !CSS.highlights ||
      !CSS.supports('selector(::highlight(demo))')) {
    status.textContent = 'Unsupported';
  } else {
    const text = document.getElementById('text').firstChild;
    const range = new Range();
    range.setStart(text, 6);
    range.setEnd(text, 10);
    CSS.highlights.set('demo', new Highlight(range));
    status.textContent = range.toString();
  }
</script>

Result

Beta

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources