Topic 59 of 62
Keyframe Animations
Overview
Transitions only go from Point A to Point B. Keyframe animations (@keyframes) allow you to choreograph complex, multi-stage sequences (Point A to B to C to D) that can run infinitely, loop, pause, and trigger automatically on page load without needing a hover state. This is how loading spinners, bouncing notifications, and complex SVG drawing effects are built natively in CSS.
Syntax
css
/* 1. Define the Choreography */
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.5); opacity: 0.5; }
100% { transform: scale(1); opacity: 1; }
}
/* 2. Apply it to an element */
.loading-dot {
/* Shorthand: name | duration | easing | delay | iteration-count | direction */
animation: pulse 2s ease-in-out 0s infinite normal;
/* Or longhand: */
animation-name: pulse;
animation-duration: 2s;
animation-iteration-count: infinite; /* Loops forever */
}Common Pitfalls
- Forgetting the
animation-fill-mode: forwardsproperty. By default, when a keyframe animation reaches 100%, the element violently snaps back to its 0% state. If you want the element to physically stay at its 100% resting state after the animation finishes, you must declareforwards. - Animating expensive properties. If your
@keyframesanimatewidth,height,margin, ortop/left, you are forcing the browser to recalculate the entire page layout 60 times a second. This causes severe lag. Only animatetransformandopacity.
Interview Questions
Q:
What is the difference between a CSS Transition and a CSS Animation?
A:
Transitions strictly interpolate between two states (A to B) and require an explicit trigger (like a hover or class toggle). Animations can have infinite complex keyframe steps (0%, 25%, 100%), can run automatically, and can loop infinitely.
Real-World Example
A classic spinning loading circle.
example
css
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
width: 50px;
height: 50px;
border: 4px solid #f3f3f3;
border-top: 4px solid blue;
border-radius: 50%;
/* 'linear' ensures it spins robotically without slowing down */
animation: spin 1s linear infinite;
}Check Your Knowledge
Test your understanding of Keyframe Animations with these quick questions.