CSS Animations and Motion
Learn keyframes, animation properties, sequencing, infinite animations, reduced-motion accessibility, and production motion practices.
Keyframe Animations
CSS animations use @keyframes to define intermediate states. An element can then reference the keyframe sequence through the animation property.
Unlike transitions, animations can run independently of a direct state change and can contain multiple keyframes.
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.card {
animation: fade-in 400ms ease-out both;
}The keyframes define the beginning and ending states and the animation declaration controls how they are played.
@keyframesdefines animation states.CSS animations can run without a hover or focus state.
Which at-rule defines CSS animation keyframes?
Animation Properties
Important animation properties include animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state.
The animation shorthand combines these properties.
.loader {
animation:
spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}The animation loops forever because the iteration count is infinite.
The animation shorthand combines multiple animation properties.
Infinite animations should be used carefully because continuous motion can be distracting.
Which value makes an animation repeat indefinitely?
Reduced Motion Accessibility
Some users request reduced motion through their operating-system accessibility preferences. CSS can respond using prefers-reduced-motion: reduce.
Decorative motion should generally be reduced or removed for these users, while essential state transitions should remain understandable.
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}The media query detects a user preference for reduced motion.
Respect user motion preferences.
Do not use motion as the only way to communicate important information.
Which media feature detects a user's reduced-motion preference?