Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 139 ยท Modern CSS

CSS Houdini and the Paint API

Meet CSS Houdini: try the Typed OM and registerProperty, and see how a paint worklet draws a custom background, with fallbacks for browsers without support.

CSS is a closed language: browsers decide which properties exist, and for years, if you wanted a new effect, you waited for the standards process or hacked around it with extra elements and JavaScript. Most CSS engine work was a black box that developers could only influence from the outside.

CSS Houdini is a family of low-level APIs that open parts of that box. They let your JavaScript hook into the browser's styling and rendering pipeline: describe your own properties, read and write CSS values as typed objects instead of strings, and even paint backgrounds with code. The name is a nod to escape artists: your code "escapes" the limits of CSS.

Support is mixed. Some pieces are everywhere (the Typed OM and custom property registration), some are only in Chromium-based browsers (the Paint API), and some remain experimental. This lesson explains the big picture, runs the parts that work in the sandbox, and shows the Paint API as a progressive enhancement. It builds on Registered Custom Properties and CSS Functions.

The Houdini family

flowchart TB
  A["CSS Houdini"] --> B["Properties and Values API<br/>registerProperty / @property"]
  A --> C["Typed OM<br/>values as objects"]
  A --> D["Paint API<br/>paint worklet"]
  A --> E["Animation, Layout, Parser APIs<br/>experimental or limited"]

Houdini is a set of APIs rather than one feature.

API What it gives you Support
Properties and Values API Typed custom properties with defaults and inheritance rules, so they can be animated Widely supported (@property in CSS, CSS.registerProperty() in JS)
Typed OM Read and write CSS values as objects (CSS.px(10)) instead of parsing strings Chromium and Safari; check Firefox
Paint API A JavaScript function that draws an image used wherever CSS accepts an image Chromium-based browsers
Animation Worklet, Layout API Run animation and layout code off the main thread Experimental, limited

You will rarely need all of them. Think of Houdini as a toolbox: the registered properties are already part of everyday CSS, the Typed OM is a convenience for animation-heavy code, and the Paint API is a way to add effects CSS cannot yet express.

Properties and Values: registering from JavaScript

You saw @property in the previous lessons. Houdini's original form is the JavaScript call CSS.registerProperty(), which does the same thing: it gives a custom property a type (syntax), a default (initialValue) and an inheritance rule. The big payoff is that a registered property becomes animatable: the browser knows how to interpolate a <number> or <angle>, which it cannot do for an untyped variable.

Animate a registered number

Hover the gauge or press the button. With the registration, --pct is a real number, so the browser can interpolate it and the pie fills smoothly. Without registration, the same transition would jump straight to the end value, because to the browser the variable is just text.

A few rules: you can register a name only once per document (a second call throws InvalidModificationError), and initialValue must be a valid value for the syntax. Because JavaScript runs after parsing, the CSS @property rule is usually the better choice for production.

The Typed OM: values as objects

Normally JavaScript sees CSS values as strings, and doing arithmetic means parsing text: parseFloat(el.style.width) + 10 + "px". The CSS Typed Object Model gives values proper types.

  • element.attributeStyleMap accesses inline styles as typed values.
  • element.computedStyleMap() reads computed styles as typed values.
  • The global CSS object has factories: CSS.px(10), CSS.percent(50), CSS.deg(45), CSS.number(2).
Typed values instead of strings

Each click reads a typed CSSUnitValue, adds 20 to its numeric value and writes a new typed value back. No string slicing is required. Typed OM is also faster for animation loops because the browser does not reparse strings every frame, and CSSMathValue objects can represent calc() expressions without text manipulation. For everyday scripts the plain style property is fine, and the Typed OM is worth adopting when you do heavy style math.

The Paint API in one picture

The Paint API lets JavaScript draw an image that CSS can use anywhere it accepts one: background-image, border-image, mask-image, list-style-image. You write a paint worklet, a small script that runs in a special isolated context and draws on a canvas-like surface. Then CSS invokes it with paint(name).

flowchart LR
  A["paint worklet module<br/>registerPaint(name, class)"] --> B["CSS.paintWorklet.addModule(url)"]
  B --> C["CSS: background: paint(name)"]
  C --> D["Browser calls paint() when<br/>size or inputs change"]

A worklet registers a painter; CSS calls it by name whenever it needs a picture.

A worklet module has this shape:

JavaScript
registerPaint("checker", class {
  static get inputProperties() {
    return ["--checker-size", "--checker-color"];   // CSS properties it reads
  }

  paint(ctx, size, props) {
    const cell = parseInt(props.get("--checker-size")) || 20;
    ctx.fillStyle = props.get("--checker-color").toString() || "#888";
    for (let y = 0; y < size.height; y += cell) {
      for (let x = 0; x < size.width; x += cell) {
        if (((x / cell) + (y / cell)) % 2 === 0) ctx.fillRect(x, y, cell, cell);
      }
    }
  }
});
  • registerPaint(name, class) declares the painter.
  • inputProperties lists the CSS properties (usually custom properties) the painter depends on. When any of them changes, the browser repaints automatically, so you can animate them.
  • paint(ctx, size, props) receives a restricted 2D context (similar to the canvas API, minus text drawing and pixel reads), the size of the box and the property values.

The HTML page loads the worklet with CSS.paintWorklet.addModule("checker.js"), and the CSS uses it:

CSS
.panel {
  --checker-size: 24;
  --checker-color: #cbd5e0;
  background: paint(checker);
}

Running one here

Worklets normally come from a separate JavaScript file. To keep this demo self-contained, the script below creates the module as a Blob and loads it from a Blob URL. It then falls back gracefully when the browser (or the sandbox) refuses the Paint API.

A checkerboard painted by a worklet

If the worklet loads, dragging the slider changes --checker-size and the browser re-runs paint() automatically, with no JavaScript touching the canvas again. If it does not (a very likely outcome outside Chromium, or in a restricted frame), the panel keeps the plain conic-gradient fallback, which is the whole point of writing it in this order. The first background declaration is the fallback; the second one is dropped by browsers that do not understand paint().

Worklets run off the main thread in a separate global scope. They cannot touch the DOM, window or the network, which makes them safe and fast, and is why they get only properties through inputProperties.

When to use Houdini

Good fits:

  • Visual effects CSS cannot express yet (custom borders, ripples, noise, blobs), with a graceful fallback.
  • Typed, animatable design tokens (registered properties). This is the most practical use today.
  • Animation-heavy tools where parsing strings every frame is a measurable cost (Typed OM).

Poor fits:

  • Anything that must look identical in every browser. Use an SVG, a canvas or an image.
  • Simple effects that gradients, clip-path or mask can already do.
  • Layout. The Layout API remains experimental. Use Grid and Flexbox.

Always:

  1. Write the fallback first, then enhance.
  2. Test with @supports (background: paint(x)), which is true where the Paint API exists, or check CSS.paintWorklet in JavaScript.
  3. Keep painters cheap: they may run on every resize and property change.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does registering --pct as a <number> make it animatable?

    An unregistered custom property is just text and cannot be interpolated. A typed registration lets transitions and keyframes blend the values.
  2. 2. What does the Typed OM change compared with el.style?

    Typed values have numeric value and unit fields, so you can do arithmetic without parsing strings.
  3. 3. In a paint worklet, how does the painter learn the values of CSS custom properties?

    Worklets are isolated from the DOM. Properties listed in inputProperties are passed to paint(), and changes trigger a repaint.
  4. 4. Why should a paint() background always have a fallback declaration before it?

    Invalid declarations are dropped, so the last valid one wins. Putting a plain background first guarantees something sensible everywhere.

Summary

  • Houdini is a set of APIs that let JavaScript extend CSS: the Properties and Values API, the Typed OM, the Paint API and experimental layout and animation worklets.
  • Registered custom properties (@property or CSS.registerProperty()) give variables a type, so they animate; this is the most widely supported part.
  • The Typed OM exposes CSS values as objects (CSS.px(), computedStyleMap(), attributeStyleMap) for cleaner, faster style math.
  • A paint worklet draws an image through registerPaint() and is used with paint(name); it reads properties through inputProperties and repaints when they change.
  • Support is uneven, so write the fallback first and detect features before relying on them.

Next lesson: Dark Mode, where you let the page follow the viewer's color scheme preference.