⚡IntermediateCSS Animations
CSS Keyframe Animations
Define multi-step animations with @keyframes and the animation property for looping, sequenced visual effects.
Overview
CSS `@keyframes` animations go beyond transitions by letting you define multiple intermediate states for an animation. While a transition animates between two states (base and hover), a keyframe animation can have unlimited steps and runs independently of user interaction.
Two parts work together:
1. **@keyframes rule**: defines the animation steps by name
2. **animation property**: attaches the keyframes to an element with timing, iteration, and fill-mode
Keyframe stops can be defined as `from`/`to` (equivalent to `0%` / `100%`) or as percentages for precise timing control.
For performance, stick to animating **opacity** and **transform** these are GPU-accelerated and won't cause layout reflows.
Key Points
- •@keyframes name { from { } to { } } defines a named animation sequence
- •animation-name links an element to a @keyframes block
- •animation-duration sets how long one cycle takes (e.g., 1s, 400ms)
- •animation-iteration-count: infinite loops forever; a number runs that many times
- •animation-fill-mode: forwards keeps the last keyframe state after the animation ends
- •animation-direction: alternate plays forward then backward on each iteration
- •Animating opacity and transform is GPU-accelerated avoid width, height, margin
Examples
Fade-in animation on page load
@keyframes fadeIn {
from { opacity: 0; transform: translateY(12px); }
to { opacity: 1; transform: translateY(0); }
}
.hero-title {
animation: fadeIn 0.6s ease-out forwards;
}forwards keeps the element visible (opacity: 1) after the animation finishes.
Infinite spinner for loading states
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
width: 40px;
height: 40px;
border: 3px solid #e5e7eb;
border-top-color: #6366f1;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}linear keeps the rotation speed constant throughout the spin.
Multi-step pulse animation
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.08); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
.notification-badge {
animation: pulse 1.5s ease-in-out infinite;
}Common Mistakes
- Forgetting animation-fill-mode: forwards element snaps back to original state after finishing
- Animating layout-affecting properties like width, height, top, margin use transform instead
- Not prefixing animation with the vendor prefix in very old browsers (not needed in modern browsers)
Note
For staggered animations (items appearing one after another), add different animation-delay values to each item: nth-child(1) { animation-delay: 0s; }, nth-child(2) { animation-delay: 0.1s; }, etc.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4