Syntax Highlighting code snippets with Prism and the Custom Highlight API – Bram.us

February 19, 2024

The CSS Custom Highlight API offers a mechanism for styling arbitrary ranges of a document identified by script. Custom highlights are represented by Highlight objects. These objects hold one or more Ranges that identify which parts of the text should be highlighted. Finally, these Highlights need to be registered into the highlight registry so that you can style them from within CSS.

Source: Syntax Highlighting code snippets with Prism and the Custom Highlight API – Bram.us

You’ve no doubt seen code examples with syntax highlighting on the Web. If you were game enough to peer under the hood with dev tools, you’d see a the DOM full of span elements.

But as I recently learned (and OI do try to keep up), a new, and already well supported Custom Highlight API, (recent Chrome (105) and Safari (17.2), currently experimental Firefox support in Nightlies) let’s us “style arbitrary ranges of a document identified by script”.

Very useful for the somewhat obscure (for most people) use case of code highlighting, I can imagine other uses such as collaborative highlighting (for example like Medium’s). While it uses JavaScript to define ranges, it uses CSS for styling them.