~ 2 min read

Next level CSS variables with @property

CSS Houdini is a set of low-level APIs that expose parts of the CSS rendering engine, and give developers access to the CSS Object Model.

This is a massive step for the CSS as a whole. It enables developers to extend CSS by hooking into the styling and layout process of a browser, telling it how to read and parse custom CSS without the need for browsers to have built in support for features.

The Properties and Values API gives your CSS custom properties superpowers by giving them semantic meaning and even fallback values, enabling CSS testing.

One small step

Below is an example of setting a custom property but with all the juicy stuff that will take our property to the next level. You can do this one of two ways, with javascript or with CSS.

CSS.registerProperty({
  name: '--colorPrimary',
  syntax: '<color>',
  initialValue: '#fab005',
  inherits: false
});
@property --colorPrimary {
  syntax: '<color>';
  initial-value: #fab005;
  inherits: false;
}

We can now use --colorPrimary just like any other custom property. The difference is now CSS knows what data type --colorPrimary is and is no longer treated like a string.

Syntax

With the syntax property, you can now write semantic CSS by specifying a type. The current types are:

  • length
  • number
  • percentage
  • length-percentage
  • color
  • image
  • url
  • integer
  • angle
  • time
  • resolution
  • transform-list
  • transform-function
  • custom-ident (a custom identifier string)

Setting a syntax enables the browser to type-check custom properties. This has many benefits.

An example of this would be a CSS animated gradient. Without the use of the @property a smooth animation between gradient values is impossible because CSS would parse the gradients values at a string. Below is a live example of an animated gradient, the example showcases the angle syntax.