Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSS

Animate gradients using @property

A gradient jumps on hover because its custom property is untyped. Register it with @property and the browser interpolates the stop.

You want a gradient to slide on hover, so you put the stop position in a custom property and add a transition. On hover the gradient jumps to the end state, even with a 400 ms transition declared.

.card {
  --stop: 20%;
  background: linear-gradient(90deg, #4f46e5 var(--stop), #0ea5e9);
  transition: --stop 400ms ease;
}

.card:hover {
  --stop: 80%;
}

I hovered the card in Chromium and read --stop from getComputedStyle every 100 ms. It was 80% on the first read and stayed there.

The browser treats an unregistered custom property as a token sequence. Its animation type is discrete, so a default transition skips the change.

Register the property

@property tells the browser the type. With a type, --stop becomes a percentage the browser can interpolate, and the transition works.

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

.card {
  background: linear-gradient(90deg, #4f46e5 var(--stop), #0ea5e9);
  transition: --stop 400ms ease;
}

.card:hover {
  --stop: 80%;
}

I ran the same hover test with this stylesheet.

registered 20%  44.5106%  68.1293%  77.6275%  80%

The value moves through the middle on its way to 80%, and the gradient stop follows. The exact values depend on when you sample.

The three descriptors

syntax is the type, written as a string such as "<percentage>", "<color>" or "<angle>". inherits says whether children inherit the value. initial-value is what the property is before you set it, which is why the .card rule no longer needs its own --stop: 20%.

MDN says the rule is ignored if syntax or inherits is missing. It is also ignored when the syntax is a specific type and initial-value is missing. With a typed syntax, the initial value must be computable without context. For example, 10px works for <length>, while 3em depends on a font size.

Pick the syntax to match what you animate. A stop position is a <percentage>.

The start angle of a conic-gradient is an <angle>, and I saw it move from 0deg to 180deg in steps. A gradient color is a <color>, and its value passed through rgb(120, 68, 195) on the way from indigo to rose.

Transition the property

Put the transition on the custom property. Writing transition: background 400ms does nothing here. With the property registered and transition: background, --stop read 80% on every sample, the same jump as before.

The @property page on MDN marks it as available across the latest browsers since July 2024.