Animations and @keyframes
10 min read
Defining and Running Animations
While transitions animate between two states (start and end), CSS animations let you define multiple keyframes and loop, reverse, or pause them. They are defined with @keyframes and applied with the animation property.
css
/* Define the keyframes */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(24px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
/* Apply an animation */
.hero-text {
animation: fadeInUp 600ms ease-out both;
}
/* Loader spinner */
.spinner {
width: 32px;
height: 32px;
border: 3px solid #e2e8f0;
border-top-color: #6366f1;
border-radius: 50%;
animation: spin 700ms linear infinite;
}
/* Full shorthand: name duration timing delay iteration direction fill-mode */
.badge {
animation: pulse 2s ease-in-out 0s infinite normal both;
}Respecting User Preferences
css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}Always include a prefers-reduced-motion media query. Some users experience nausea or seizures from motion. Disabling or reducing animations for them is a basic accessibility requirement.
Ready to test yourself?
Practice CSS— quiz & coding exercises