Advanced CSS
Animation
Master CSS Animations, covering animation parameters, iteration loops, direction rules, fill modes, play states, and performance optimization.
1. Learning Objectives
In this lesson, you will master creating complex multi-stage CSS animations. By the end of this topic, you will be able to:
- Identify the components of a CSS animation (name, duration, iteration-count, and fill-mode).
- Control how styles are applied before and after an animation using
animation-fill-mode. - Manage animation loops and directions using
iteration-countanddirection. - Pause and resume animations using
animation-play-state. - Build high-performance, looping loading spinners and skeleton loaders.
2. Overview
CSS Animations allow you to create complex, multi-stage animations that run automatically. Unlike transitions, which only animate between a starting and ending state when triggered, animations use keyframe rules to define intermediate styles and control loops, directions, and play states.
3. Why This Topic Matters
Animations add motion and improve user feedback, but poor configuration causes issues:
- Instant Reset Snap: By default, an animation snaps back to its starting state immediately when it finishes. You must configure
animation-fill-mode: forwardsto keep the final animation styles on the element. - CPU Drain: Looping animations that transition layout properties (like height or margins) force constant page reflows, causing devices to run hot and drain battery.
4. Real-World Analogy
Think of a CSS animation like **a wind-up toy train running on a track**:
- The Route Map (Keyframes): Drawing specific stops (e.g. stop at 0% start, 50% midpoint turn, 100% station arrive).
- The Journey Time (duration): Setting the clock to complete the loop in exactly 10 seconds.
- The Run Cycles (iteration-count): Winding up the train to run the track twice (2) or loop infinitely (infinite).
- The Station Stop (animation-fill-mode):
- None: The train instantly teleports back to its starting garage when the run finishes.
- Forwards: The train stops and parked at the final station platform when the run completes.
5. Core Concepts
CSS animations are defined using several properties:
- animation-name: The name of the
@keyframesblock that defines the animation. - animation-duration: The time it takes to complete one cycle.
- animation-iteration-count: The number of times the animation plays (e.g.
3,infinite). - animation-fill-mode: Controls what styles are applied to the element when the animation is finished or delayed (e.g.
none,forwards,backwards,both).
| Fill-Mode Value | Behavior |
|---|---|
| none | The element returns to its original styles as soon as the animation completes. (Default). |
| forwards | The element retains the styles defined in the final keyframe when the animation ends. |
| backwards | The element applies the styles defined in the first keyframe during the delay period before the animation starts. |
| both | Applies both forwards and backwards behaviors. |
6. Syntax & API Reference
Below is the syntax comparing individual properties and the animation shorthand declaration:
7. Visual Diagram
This diagram displays how the browser checks and runs CSS animation cycles:
8. Live Example — Full Working Code
A sample HTML document showcasing loading spinners and pulse animations:
9. Interactive Playground
Try It Yourself Challenges:
- Remove the
forwardsparameter from the slide-box animation declaration and notice how the element snaps back to its starting state when the animation ends. - Change the
animation-play-statetopausedon the spinner hover state.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Missing forwards fill-mode | Forgetting to set forwards fill-mode, causing elements to snap back to their start states when the animation finishes. | animation: fade-in 1s; (snaps to transparent at end) |
animation: fade-in 1s forwards; |
| Duplicate @keyframes declarations | Declaring duplicate @keyframes rules with the same name, causing the browser to ignore the earlier rules. | Multiple @keyframes spin defined. |
Ensure all @keyframes blocks have unique names. |
11. Best Practices
- Use forwards to retain final styles: Always use
animation-fill-mode: forwardswhen you want elements to retain their final animation styles when they finish. - Use GPU-friendly properties for loops: Stick to animating
transformandopacityproperties for infinite loops (like loading spinners) to prevent layout reflow lag. - Use the animation shorthand: Use the
animationshorthand to write cleaner code and prevent property override conflicts.
12. Browser Compatibility
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| CSS Animations and @keyframes | Supported (26+) | Supported (16+) | Supported (6.1+) | Supported (12+) |
13. Interview Questions
🟢 Q1: How does animation-fill-mode: forwards differ from animation-fill-mode: both?
Answer: forwards ensures the element retains its final animation styles when the animation finishes. both combines forwards and backwards behaviors: the element applies the starting animation styles during the delay period before the animation begins, and retains the final animation styles when the animation ends.
14. Debugging Exercise
Identify why the fade-in element snaps back to transparent after completing the animation, and fix the CSS configuration:
Diagnosis: By default, elements snap back to their original styles immediately when their animation finishes. To make the toast message retain its final opacity: 1 style, append the forwards parameter to the animation declaration.
Fixed CSS:
15. Practice Exercises
Exercise 1: Bouncing Notification Badge
Build a notification badge. Create a keyframe animation that translates the badge vertically to create a bouncing effect. Configure it to loop 3 times when the badge is hovered.
16. Scenario-Based Challenge
The Skeleton Loader Shimmer Challenge:
An article list page displays gray placeholder layout boxes (skeleton screens) while loading content. The design requires a soft shimmer animation that runs horizontally across the cards to suggest a loading state. Outline a CSS keyframe animation strategy using background gradient variables to implement this shimmer loader.
17. Quick Quiz
Q1: Which animation fill mode retains the final keyframe styles when the animation finishes?
A) backwards
B) forwards
C) none
Answer: B — The forwards fill mode retains the styles defined in the final keyframe when the animation ends.
18. Summary & Key Takeaways
- • Use keyframes to build complex, multi-stage animations with custom loop cycles.
- • Configure forwards fill mode to keep elements at their final animation styles when they finish.
19. Cheat Sheet
| Property | Visual Layout Action |
|---|---|
animation-play-state: paused; |
Pauses an active CSS animation on the element. |