The ::highlight()
CSS pseudo-element applies styles to a custom highlight.
A custom highlight is a collection of Range
objects and is registered on a webpage using the HighlightRegistry
.
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The ::highlight()
CSS pseudo-element applies styles to a custom highlight.
A custom highlight is a collection of Range
objects and is registered on a webpage using the HighlightRegistry
.
Only certain CSS properties can be used with ::highlight()
:
color
background-color
text-decoration
and its associated propertiestext-shadow
-webkit-text-stroke-color
, -webkit-text-fill-color
and -webkit-text-stroke-width
In particular, background-image
is ignored.
::highlight(custom-highlight-name)
<p id="rainbow-text">CSS Custom Highlight API rainbow</p>
#rainbow-text { font-family: monospace; font-size: 1.5rem; } ::highlight(rainbow-color-1) { color: #ad26ad; text-decoration: underline; } ::highlight(rainbow-color-2) { color: #5d0a99; text-decoration: underline; } ::highlight(rainbow-color-3) { color: #0000ff; text-decoration: underline; } ::highlight(rainbow-color-4) { color: #07c607; text-decoration: underline; } ::highlight(rainbow-color-5) { color: #b3b308; text-decoration: underline; } ::highlight(rainbow-color-6) { color: #ffa500; text-decoration: underline; } ::highlight(rainbow-color-7) { color: #ff0000; text-decoration: underline; }
const textNode = document.getElementById("rainbow-text").firstChild; if (!CSS.highlights) { textNode.textContent = "The CSS Custom Highlight API is not supported in this browser!"; } // Create and register highlights for each color in the rainbow. const highlights = []; for (let i = 0; i < 7; i++) { // Create a new highlight for this color. const colorHighlight = new Highlight(); highlights.push(colorHighlight); // Register this highlight under a custom name. CSS.highlights.set(`rainbow-color-${i + 1}`, colorHighlight); } // Iterate over the text, character by character. for (let i = 0; i < textNode.textContent.length; i++) { // Create a new range just for this character. const range = new Range(); range.setStart(textNode, i); range.setEnd(textNode, i + 1); // Add the range to the next available highlight, // looping back to the first one once we've reached the 7th. highlights[i % 7].add(range); }
Desktop | Mobile | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | |
::highlight |
105 | 105 | previewCannot yet be used withtext-decoration and text-shadow . |
91 | 17.2 | 105 | NoCannot yet be used withtext-decoration and text-shadow . |
72 | 17.2 | 20.0 | 105 |
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/::highlight