CSS: animation
The animation property is a shorthand for running a CSS keyframe animation.
What you will learn
- How
@keyframesdescribes the stages of motion - How duration, timing, and repetition affect an animation
- How to respect a user's reduced-motion preference
Basic example
.notice {
animation: fade-in 300ms ease-out both;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(.5rem);
}
to {
opacity: 1;
transform: translateY(0);
}
}The shorthand usually includes the animation name, duration, timing function, and fill mode. The name must match a @keyframes rule.
Useful options
animation-durationsets the time for one cycle.animation-iteration-count: infiniterepeats the animation forever. Use this sparingly.animation-fill-mode: bothkeeps the styles from the first or last keyframe outside the active time.
Reduced motion
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms;
animation-iteration-count: 1;
scroll-behavior: auto;
}
}Keep important information available without motion. Do not make animation the only way to communicate a state.
Common mistakes
- Do not use an animation name without defining the matching keyframes.
- Keep looping motion subtle and provide a way to pause or stop it when appropriate.
- Preserve visible focus styles and check the result on small screens.