Chapter 17. CSS

Introduction

In the modern browser environment, CSS not only lets you write style rules but also has a set of APIs you can use to further enhance your application.

The CSS Object Model (CSSOM) allows you to set inline styles programmatically from JavaScript code. Not only that, but you can even change the values of CSS variables at runtime.

In Chapter 8, you saw an example of using window.matchMedia to programmatically check a media query to see if it matches on the current page.

This chapter has some helpful recipes that use some of these CSS-related APIs. At the time of writing, some of these APIs do not have good browser support. Always check browser compatibility before using them.

Highlighting Text Ranges

Problem

You want to apply a highlight effect to a range of text in the document.

Solution

Create a Range object around the desired text, then use the CSS Custom Highlight API to apply the highlighting styles to that range.

The first step is to create a Range object. This object represents a region of text within the document. Example 17-1 shows a general purpose utility function to create a range given a text node and the text to highlight.

Example 17-1. Creating a Range
/**
 * Given a text node and a substring to highlight, creates a Range object covering
 * the desired text.
 */
function getRange(textNode, textToHighlight) {
  const startOffset = textNode.textContent.indexOf(textToHighlight);
  const endOffset = startOffset + textToHighlight.length

Get Web API Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.