Animation using @keyframes
CSS can animate on its own, no JavaScript required. It takes two steps.
1. Define the movement
@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
@keyframes names a sequence. On its own it does nothing at all.
For more than two steps, use percentages:
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.4); }
100% { transform: scale(1); }
}
2. Attach it
.slide {
animation: slide 1.5s ease-in-out infinite alternate;
}
That shorthand is: name, duration, easing, how many times, direction. alternate runs it forwards then backwards, which stops the jarring snap back to the start.
transition vs animation
transition animates between two states, usually triggered by :hover. animation runs a sequence on its own, without anything triggering it. Reach for transition first ~ it’s simpler, and it covers most of what you want.
Animate the cheap things
transform and opacity are almost free for a browser to animate. width, height, top and margin force it to re-measure the whole page every frame, and things get choppy fast. If you can express a movement as a transform, do.
Please include this
@media (prefers-reduced-motion: reduce) {
* { animation: none; }
}
Motion makes some people genuinely unwell, and their device already knows they’ve asked for less of it. Three lines.
Click to resume
Use the console below.