A transition moves an element between two states. When motion needs a stop along the way—or needs to return to its starting point—use a keyframe animation. An `@keyframes` rule names the animation and defines selected points on its timeline. The browser fills in the frames between them. section 17.0
Defining the motion and playing it are separate steps:
- Inside `@keyframes`, percentages mark progress: `0%` is the beginning, `50%` the midpoint, and `100%` the end. Each block declares the property values wanted at that point. section 17.1
- Apply the named animation to an element with `animation`. Its shorthand can specify the name, duration, timing function, and iteration count. section 17.1 section 17.7
Move a box out and back
@keyframes over-and-back { 0% { background-color: hsl(0, 50%, 50%); transform: translate(0); } 50% { transform: translate(50px); } 100% { background-color: hsl(270, 50%, 90%); transform: translate(0); } } .box { animation: over-and-back 1.5s linear 3; } The box moves right, returns, and repeats three times. Its color changes smoothly from the first keyframe to the last even though no color is declared at `50%`: a property need not appear in every keyframe. section 17.1
Intermediate keyframes can control *when* different parts of a motion happen. In a card fly-in, `translateZ()` brings cards most of the way forward before the final keyframe completes their rotation; opacity fades them in along the way. The containing grid supplies perspective. section 17.2.2
Listing 17.14 Defining the shake animation
.shake {
animation: shake 0.7s linear;
}
@keyframes shake {
0%, #1
100% { #1
transform: translateX(0);
}
10%,
30%,
50%,
70% {
transform: translateX(-0.4em); #2
}
20%,
40%,
60% {
transform: translateX(0.4em); #3
}
80% { #4
transform: translateX(0.3em); #4
} #4
90% { #4
transform: translateX(-0.3em); #4
} #4
} #4
The shake animation groups percentages that share a declaration: several points move the button left, others move it right, and the beginning and end share its default position. Smaller movements near the end make the shake taper off. section 17.4.2
Keyframes define reusable motion, not the moment it must play. A class can apply the shake to a Save button, while JavaScript adds that class after typing pauses and removes it when the animation ends. Use that timing to make motion a useful reminder rather than mere decoration. section 17.4.2 section 17.7


