2 min read

CSS Properties and Values API (Houdini)

The CSS Properties and Values API is part of the CSS Houdini project. It allows developers to explicitly define their custom CSS properties (CSS variables), specifying their type, initial value, and inheritance behavior.

1. The Problem: Untyped Variables

Standard CSS variables (Custom Properties) are untyped strings.

:root {
  --my-color: red;
  --my-size: 10px;
}

The browser doesn't know that --my-color is a color or --my-size is a length. This leads to limitations:

  • No Transitions: You cannot transition a gradient if the browser doesn't know the variable inside it is a color.
  • No Validation: You can assign "hello" to --my-size, and the browser won't complain until it tries to use it.

2. The Solution: CSS.registerProperty

This API allows you to register a property with a specific syntax definition.

if ('registerProperty' in CSS) {
  CSS.registerProperty({
    name: '--my-color',
    syntax: '<color>',
    inherits: false,
    initialValue: 'black',
  });
}

3. Configuration Options

  • name: The name of the custom property (must start with --).
  • syntax: Describes the allowed value type (e.g., <color>, <length>, <number>, <percentage>, *).
  • inherits: Boolean. Whether the property inherits by default (like color) or not (like border).
  • initialValue: The default value if not specified. Required if syntax is not *.

4. Enabling Transitions on Gradients

One of the "killer features" of this API is enabling transitions on properties that were previously impossible to animate, like gradients.

Without API: If you change a variable inside a gradient, it snaps instantly because the browser sees it as a string change.

With API: Because the browser knows --stop-color is a <color>, it can interpolate between values.

CSS.registerProperty({
  name: '--stop-color',
  syntax: '<color>',
  inherits: false,
  initialValue: 'blue',
});
.box {
  --stop-color: blue;
  background: linear-gradient(to right, white, var(--stop-color));
  transition: --stop-color 1s;
}

.box:hover {
  --stop-color: red; /* This will now fade smoothly from blue to red! */
}

programming/javascript/vanilla/javascript programming/javascript/vanilla/css-houdini programming/javascript/vanilla/dom-manipulation