2 min read

Animating gradients with @property

For years, hovering a button with a gradient meant a hard jump between two backgrounds. Registering the colors as custom properties finally lets the browser animate them smoothly.

Pink and blue fluid paint flowing into each other

Browsers can transition colors, lengths and numbers, but a background-image is an image. When you change one gradient to another, there is nothing in between to interpolate, so the change happens in a single frame. The trick is to animate the inputs of the gradient instead of the gradient itself.

Register the colors

With @property you tell the browser that a custom property is a color. From then on, it knows how to blend two values and every gradient using the property updates on each frame.

css
@property --from {
    syntax: '<color>';
    inherits: false;
    initial-value: #6D4AFF;
}

.button {
    background: linear-gradient(120deg, var(--from), #FF5FB1);
    transition: --from 0.6s ease;
}

.button:hover {
    --from: #2DD4F0;
}

Rotate angles, not images

The same works for angles and percentages. Register an <angle> and animate it with keyframes to get a slowly rotating conic gradient, the glow behind the call to action on this site works exactly like that.

Tip

Keep the number of animated properties small. Each one makes the browser repaint the whole element on every frame.

Respect reduced motion

Ambient animation is decoration. Wrap it in @media (prefers-reduced-motion: no-preference) so people who get dizzy from moving backgrounds see a calm, static gradient instead.