Houdini in CSS

Mateusz -

CSS Houdini  – APIs collection that exposes parts of the CSS engine. One of the Houdini features is an opportunity to use type checking and default values in our styles.

Defining variables

In CSS when we want to declare a variable we usually do it inside :root. But there is one big problem with that approach. Everyone can change this variable to any value. It could be a number, some other property, it could be anything but a color.

/* */
:root {
  --primary-color: gold;
}

.text {
  color: var(--primary-color);
}
/* */

@property keyword

In Houdini CSS there is a property at-rule keyword. It allows us to create something like TypeScript in CSS, because here we can define the valid value for our variable. This approach will ensure that the given value is valid. Therefore, it will block any attempt to change the value of the variable, even using browser console.

/* */
@property --primary-color {
  syntax: "<color>";
  inherits: false;
  initial-value: gold;
}
/* */

Registering @property using JavaScript

//
window.CSS.registerProperty({
  name: "--primary-color",
  syntax: "<color>",
  inherits: false,
  initialValue: "gold"
});
//

@property parameters overview

Most useful syntax properties:
"<length>",
"<number>",
"<percentage>",
"<length-percentage>",
"<color>",
"<image>",
"<url>",
"<integer>"

inherits: boolean
initialValue: valid value for chosen syntax

Summary

CSS syntax slowly evolves. If we want to write safer styles, then that would be a good idea to consider using this feature. More about Houdini CSS can be found here devMozilla.