Custom Highlight API (::highlight()) + ::target-text
Custom highlights Baseline 2025 (Chrome 105, Safari 17.2, Firefox 140). `::target-text` Baseline 2025 (Chrome 89, Safari 18.2, Firefox 131).
Chrome 105
Edge 105
Safari 17.2
Firefox 140
Estiliza rangos de texto arbitrarios (coincidencias de búsqueda, corrector, tokens de código) sin envolverlos en spans, mediante objetos `Highlight` en JS y `::highlight(name)` en CSS. `::target-text` estiliza el texto al que saltó una URL de fragmento de texto (`#:~:text=`).
Type-safe highlights work without changing the DOM. Highlights are cheap and fast.
CSS
.fx-026 {
font-family: system-ui
}
::highlight(fx-026-match) {
background: #fde68a;
color: #111;
text-decoration: underline wavy #d97706
}
::target-text {
background: #bfdbfe
}
HTML
<p class="fx-026">Type-safe highlights work without changing the DOM. Highlights are cheap and fast.</p>
<script>
const p=document.querySelector('.fx-026');const t=p.firstChild;const ranges=[];
const re=/highlights?/gi;let m;while((m=re.exec(t.data))){const r=new Range();r.setStart(t,m.index);r.setEnd(t,m.index+m[0].length);ranges.push(r)}
if(window.Highlight){CSS.highlights.set('fx-026-match',new Highlight(...ranges))}
</script>Fallback: Detecta `window.Highlight`; recurre a envolver las coincidencias en `<mark>` si tienes que soportar motores antiguos.
Fuente: developer.mozilla.org/en-US/docs/Web/CSS/Guides/Custom_highlight_API
Prompt
Para resaltar resultados de búsqueda o sintaxis, no inyectes envoltorios `<span>`. Construye objetos `Range` para las coincidencias, regístralos con `CSS.highlights.set('name', new Highlight(...ranges))` y estiliza con `::highlight(name)` (solo se permiten color, background, text-decoration y text-shadow). Estiliza también `::target-text` para que los enlaces profundos por fragmento de texto muestren dónde aterrizaron.