Day 84: the @property at-rule
posted on
It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.
The @property
rule allows you to register custom properties.
You can already define custom properties, but the difference between defining and registering is that the at-rule allows you to specify the type and other attributes.
@property --hue {
/* The type. */
syntax: '<angle>';
/* Is it an inhertiable property? */
inherits: false;
/* The initial value. */
initial-value: 0deg;
}
syntax
The syntax
descriptor specifies the syntax (or type) of the property. You can find a list of supported syntax component names in the spec.
@property --milliseconds {
syntax: '<integer>';
inherits: false;
}
inherits
The inherits
descriptor specifies whether the property inherits from its parent or not.
@property --color-primary {
syntax: '<color>';
inherits: true;
}
initial-value
The initial-value
descriptor specifies the initial value of the custom property.
@property --color-primary {
syntax: '<color>';
inherits: true;
initial-value: rgb(0 0 0);
}
An example
Let's say we have a <button>
and we want to transition the background color on :hover
and :focus-visible
.
button {
--h: 176;
--s: 74%;
--l: 60%;
--bg: hsl(var(--h) var(--s) var(--l));
background-color: var(--bg);
transition: background-color 1s;
}
button:is(:hover, :focus-visible) {
--h: 20;
}
That works well, we get a nice transition from the first color to the second color, but if we want to animate just the hue to get a more interesting effect, we have bad luck, because the value of --h
is a string, which you can't animate.
button {
--h: 176;
--s: 74%;
--l: 60%;
--bg: hsl(var(--h) var(--s) var(--l));
background-color: var(--bg);
transition: --h 1s;
}
With @property
we can turn the string into number and animate it.
@property --h {
initial-value: 0;
inherits: true;
syntax: '<number>';
}
button {
--h: 176;
--s: 74%;
--l: 60%;
--bg: hsl(var(--h) var(--s) var(--l));
background-color: var(--bg);
transition: --h 1.6s;
}
Further reading
Overview: 100 Days Of More Or Less Modern CSS