brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: @property gives a CSS variable a type, so you can animate it

Css
~/tips/tip-css-property-animate-variable

@property --fill {

Registers a typed CSS variable so the browser can animate and validate it.

Try to transition a CSS variable that sits inside a gradient and you’ll see it jump from one value to the other with no animation at all. The browser doesn’t know what’s in a normal custom property, so it can’t work out the values in between. @property tells it, and that one change makes a whole set of effects possible without JavaScript.

You register the variable with a type, an initial value and whether it inherits. Here’s a button whose gradient slides on hover:

@property --fill {
  syntax: "<percentage>";
  inherits: false;
  initial-value: 0%;
}

.button {
  background: linear-gradient(to right, #2f7 var(--fill), #222 var(--fill));
  transition: --fill 0.4s ease;
}

.button:hover {
  --fill: 100%;
}

Because --fill is now a real percentage, the browser can animate it from 0% to 100%, and the gradient moves with it. Without the @property block the same CSS just flips on hover. MDN uses the same trick with @keyframes for a progress bar.

The type also works as a check. If someone sets --fill: red, the value isn’t a percentage and the browser falls back to the initial-value. That’s handy in a design system where variables get passed around a lot.

The rules are strict, and that’s the main caveat. syntax and inherits are both required, and syntax must be in quotes. initial-value is required for every type except "*", and it has to be a value that doesn’t depend on anything else: 10px works, 3em doesn’t, because an em depends on the font size of the parent. Break one of those rules and the whole block is ignored without an error. If the same name is also registered with CSS.registerProperty() in JavaScript, the JavaScript version wins.

Support: Chrome and Edge 85, Safari 16.4 and Firefox 128. That makes it Baseline newly available since July 2024. In an older browser the variable still works as a normal custom property, so the button only loses the animation.

Further reading: MDN: @property, MDN: Registering CSS custom properties

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link