Animate a CSS gradient
To animate a CSS background we can use a CSS variable and animate it with a keyframe animation:
.bg {
background-image: linear-gradient(
0deg,
var(--gradient-color) 0%,
orange 100%
);
animation: bg-animation 5s infinite alternate;
}
@keyframes bg-animation {
from {
--gradient-color: red;
}
to {
--gradient-color: blue;
}
}
You will see that the animation happens, but it does not interpolate between the values, it jumps instead.
To fix this we need to tell the browser how to animate our CSS variable. This is done with the new @property
rule:
@property --gradient-color {
syntax: "<color>";
inherits: false;
initial-value: white;
}
We tell the browser that our variable is of type color
and the initial value is white
.
It also tells the browser that this variable will not be inherited by children elements. Setting it to false
is a good default because it saves the browser from additional work.
The animation is now able to interpolate the values from red
to blue
.
You can see the finished code here.