CSS Keyframe Animations
CSS keyframes describe the stages of an animation. Learn how to name an animation, set its timing and repetition, and keep motion comfortable and accessible.
Quick answer: Define animation stages with @keyframes, then apply them with the animation property. Use animations to explain a state change or draw attention briefly; avoid motion that repeats without a clear purpose.
Define a keyframe animation
This example fades a status message into view. The from and to keywords describe the first and last frames; percentages can define additional stages.
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(0.5rem);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.notice {
animation: fade-in 240ms ease-out both;
}
The shorthand sets the animation name, duration, timing function and fill mode. The both value applies the first and last keyframe styles before and after the animation.
Control duration and repetition
Animations can use animation-duration, animation-delay, animation-iteration-count and animation-direction. For a one-time entrance, use a finite iteration count. An infinite loop is best reserved for an ongoing status that needs a visible cue, and should be subtle.
.loading-dot {
animation: pulse 900ms ease-in-out infinite alternate;
}
@keyframes pulse {
from { opacity: 0.45; }
to { opacity: 1; }
}
Support reduced-motion preferences
People may request less animation in their operating system or browser. Keep the information available and remove nonessential movement when that preference is active.
@media (prefers-reduced-motion: reduce) {
.notice,
.loading-dot {
animation: none;
}
}
When should you use animations instead of transitions?
A transition is useful when a property changes between two states, such as a button hover color. Keyframes are useful when you need multiple stages, a timed entrance or a repeated sequence. For simple interface feedback, prefer a brief transition or no motion.
Why is my CSS animation not running?
Check that the animation-name matches the name after @keyframes, that the duration is greater than zero, and that the animation rule targets the intended element. Also check whether a reduced-motion rule disables it.
Practice: animate a success notice
Create a notice in HTML, define a short fade and upward movement, and apply it once when the notice appears. Add a reduced-motion media query and confirm the same message remains clear without animation.