Una Kravets has written an excellent article about a feature that has been released with Chrome 85: The @property syntax of the Properties and Values API. The Properties and Values API is part of CSS Houdini, the next generation of additions to CSS allowing developers to extend the language directly at the engine level. With the @property syntax, you can declare a variable including a type, an initial value, and even control inheritance. This is how it looks like:
@property --colorPrimary {
syntax: "<color>";
initial-value: magenta;
inherits: false;
}
The initial value ensures that if someone tries to give the --colorPrimary
an invalid value that doesn’t match the type specified by syntax
, like “20px” or “border-box”, there is still a fallback.
But there is more. The new @property syntax fixes a fundamental problem of custom properties: You could not animate them. While it was possible to animate a property that used a custom property, it wasn’t possible to animate the custom property itself because the custom property was read as a string.
Animating a background
property, for example, would work:
button {
--color: green;
background: var(--color);
transition: background .4s ease;
}
button:hover {
--color: blue;
}
But not if you wanted to apply the transition to the custom property, --color
:
button {
--color: green;
background: var(--color);
transition: --color .4s ease;
}
button:hover {
--color: blue;
}
With the new @property syntax, this now changes, because if you define a type (like length
, number
, percentage
, color
, and many more) for the custom property, the browser now knows how to transition it. The prime example that Una shows is that it is now possible to animate something that couldn’t be animated before: Gradients.
See the Pen Gradient Transitions with @property by Matthias Ott (@matthiasott) on CodePen.
When I played around with the feature myself, however, I noticed that using relative units like rem
s with a type of length
did not work properly when I tried to calculate a font-size in Chrome 85. It worked well when I used an absolute length in px
, though. Maybe I’m also overlooking something here – and if I am, please tell me – but it seems as if the new feature still needs a few more iterations until it fully works as expected.
See the Pen @property Custom Property Test: rem font-size by Matthias Ott (@matthiasott) on CodePen.
Once browser support has gotten better, the @property syntax might make many things around custom properties much more convenient. In particular when creating animations, the possibility to transition the computed value of the custom property will come in handy.
-
This is the 59th post of my 100 days of writing series. You can find a list of all posts here.
~