Day 104: animation with registered custom properties
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.
All major browsers except Firefox (coming soon!) support the @property at-rule. It enables you to do things you previously couldn't, like animating custom properties.
Let's say you have two animations. One fades an element; the other moves it. Based on their motion preference, users see one or the other.
.banner {
--animation: fade;
animation: var(--animation) 3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
}
@media(prefers-reduced-motion: no-preference) {
.banner {
--animation: move;
}
}
@keyframes move {
from { translate: 100vw; }
to { translate: 0; }
}
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}
That works nice and well, but if you use custom properties in your keyframe animations instead of redeclaring regular properties, it doesn't work anymore because you're trying to animate string values.
.banner {
--animation: fade;
translate: var(--position) 0;
opacity: var(--opacity);
animation: var(--animation) 3s cubic-bezier(0.18, 0.89, 0.32, 1.28);
}
@media(prefers-reduced-motion: no-preference) {
.banner {
--animation: move;
}
}
@keyframes move {
from { --position: 100vw; }
to { --position: 0; }
}
@keyframes fade {
from { --opacity: 0; }
to { --opacity: 1; }
}
With the @property
at-rule you can turn the two string values into a <length>
and a <number>
, which makes them animatable.
@property --position {
syntax: "<length>";
inherits: false;
initial-value: 0;
}
@property --opacity {
syntax: "<number>";
inherits: false;
initial-value: 1;
}
@keyframes move {
from { --position: 100vw; }
to { --position: 0; }
}
@keyframes fade {
from { --opacity: 0; }
to { --opacity: 1; }
}
Further reading
Overview: 100 Days Of More Or Less Modern CSS