Set an infinite animation on an element with ease. To make an element rotate forever, use this:
“`css
.box {
animation: rotate 5s infinite linear;
}
@keyframes rotate {
to { rotate: 1turn; }
}
“`
Pausing the animation is simple with:
“`css
animation-play-state: paused;
“`
Explore interactions like speeding up, slowing down, and stopping smoothly. Here’s one method for faster rotation on hover:
“`css
.box {
animation:
rotate 5s linear infinite,
rotate 5s linear infinite paused;
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes rotate {
to { rotate: 1turn; }
}
“`
This trick uses `animation-composition: add` to combine animations. Adjusting animation duration directly leads to issues, so avoid it.
For flexible code, incorporate CSS variables:
“`css
.box {
–d: 5s;
–s: 2;
–_a: rotation linear infinite;
animation:
var(–_a) var(–d),
var(–_a) calc(var(–d)/(var(–s) – 1)) paused;
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes rotation {
to { rotate: 1turn }
}
“`
Reverse a rotation by playing the second animation in reverse:
“`css
.box {
–d: 5s;
–s: .5;
–_a: rotation linear infinite;
animation:
var(–_a) var(–d),
var(–_a) calc(var(–d)/(1 – var(–s))) paused reverse;
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes rotation {
to { rotate: 1turn; }
}
“`
By varying `–s`, you control speed and direction. Negative values reverse direction, and zero stops it:
“`css
“`
Merge two codes into one generic version, accepting all `–s` values:
“`css
.box {
–d: 5s;
–s: 2;
–_a: rotation linear infinite;
animation:
var(–_a) var(–d),
var(–_a) abs(var(–d)/(var(–s) – 1)) paused;
animation-composition: add;
}
.box:hover {
animation-play-state: running;
}
@keyframes rotation {
to { rotate: 1turn }
}
“`
Avoid `reverse`; manipulate direction within the animation:
“`css
@keyframes rotation {
to { rotate: calc(sign(var(–s) – 1)*1turn) }
}
“`
This final code facilitates control using a single variable, without updating keyframes dynamically.
