Skip to main content
CSS Tip

Control the Speed of Infinite Animations

Here is a simple code that lets you adjust the speed of your infinite animation on hover (or with other interactions). It relies on animation-composition: add that allows you to run the same animation twice with an additive effect.

By pausing/running the second animation, you can make the overall animation faster, slower, or move it in the opposite direction. You can easily control this using one CSS variable.

.box {
--d: 5s; /* animation duration */
--s: 2; /* speed factor
[1 +infinite[ : move faster
]0 1[ : slow down
0: stop
]-infinity 0[ : move in the opposite direction
*/

--_a: animate linear infinite;
animation:
var(--_a) var(--d),
var(--_a) abs(var(--d)/(var(--s) - 1)) paused
if(style(--s < 1):reverse;else: ;);
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes animate {
to {/* whatever you want to animate */}
}

Here is an example using an infinite rotation where each element has a different speed factor. Hover to see the result:

See the Pen Infinite Animation Speed Control by Temani Afif (@t_afif) on CodePen.

The use of the inline condition if() is not well supported, so we can rely on the code below until better support is available:

.box {
--d: 5s; /* animation duration */
--s: 2; /* speed factor */

animation:
init linear infinite var(--d),
control linear infinite abs(var(--d)/(var(--s) - 1)) paused;
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes init {
to {rotate: 1turn}
}
@keyframes control {
to {rotate: calc(sign(var(--s) - 1)*1turn)}
}

All you have to do is change rotate with the property you want to animate.

Here is an example with an infinite marquee where I am animating the offset-distance:

See the Pen Infinite Marquee Speed Control by Temani Afif (@t_afif) on CodePen.

Another example with a glowing border effect where I am animating a CSS variable:

See the Pen Glowing border Animation with hover effect by Temani Afif (@t_afif) on CodePen.


More CSS Tips