CSS: CSS Animation
Last updated: 2026-10-13
1. @keyframes
Defines the animation sequence by specifying styles at various points:
▶ Example
▶ Try it Yourself2. animation Properties
(1) Quick Reference
| Property | Values | Purpose |
|---|---|---|
animation-name |
@keyframes name |
Animation name |
animation-duration |
1s, 500ms |
How long animation takes |
animation-timing-function |
ease, linear, ease-in, ease-out |
Speed curve |
animation-delay |
0.5s, -1s |
Delay before start |
animation-iteration-count |
1, 2, infinite |
Number of plays |
animation-direction |
normal, reverse, alternate |
Play direction |
animation-fill-mode |
none, forwards, backwards, both |
Style before/after |
(2) Shorthand
CSS
.animation {
animation: slideIn 0.5s ease-out 0.2s infinite alternate forwards;
/* name duration timing-function delay iteration-count direction fill-mode */
}
3. Common Animations
(1) Fade In
▶ Example
▶ Try it Yourself(2) Bounce
▶ Example
▶ Try it Yourself(3) Loading Spinner
▶ Example
▶ Try it Yourself4. Performance Tips
🔥 Performance warning: Don't animate too many elements at once. Animating 20-30 elements simultaneously causes jank. Use
will-change to tell browsers which elements will animate, but don't abuse it — will-change elements consume extra GPU memory.
Best properties to animate:
Avoid animating:
width,height,margin,padding(causes reflow)box-shadow(expensive to calculate)
❓ FAQ
Q What's the difference between @keyframes and transition?
A transition only handles "state A to state B" simple changes. @keyframes can define multiple keyframes (0%, 50%, 100%) for complex multi-stage animations. Simple hover effects use transition; complex auto-playing effects use @keyframes.
Q Will animation: infinite cause lag?
A Reasonable use won't. But don't animate too many elements at once (recommended no more than 20). Use
will-change to tell browsers which elements will change, helping GPU acceleration. If page drops frames, reduce animated elements or shorten duration.Q Element jumps back after animation — what to do?
A Set
animation-fill-mode: forwards — animation maintains the last frame's state after finishing. Default is none, which returns to start position.📖 Summary
@keyframesanimations are more powerful thantransition— can define multi-stage animation sequences- Through
animationsub-properties, control play count, direction, delay, fill mode, etc. - Prioritize
transformandopacityin animations for best performance - For infinite loops (like loading spinners), use
infinite
📝 Exercises
- Create a "bouncing ball" animation — ball drops, bounces, gradually weakens (using multi-stage keyframes).
- Create a "spinning loader" — a ring continuously rotating (hint: border + border-top-color + border-radius + animation).
- Create a "fade-in slide" page: title slides from top, paragraph from bottom, image from left (different animations).
- Create a "breathing light" button — button brightness cycles.