Animations
While CSS Transitions are perfect for simple "A to B" movements, CSS Animations allow for much more complex, multi-stage sequences. With animations, you aren't limited to just two states; you can define an infinite number of waypoints and control exactly how an element behaves over time.
1. The Foundation: @keyframes
Before you can apply an animation, you must define it using the @keyframes rule. This is where you set the "waypoints" (percentages) of the animation.
Code Block Loading...
2. Applying the Animation
To bring an element to life, you use the animation property. This property acts as a shorthand for several sub-properties.
The Shorthand Order: animation: [name] [duration] [timing-function] [delay] [iteration-count] [direction] [fill-mode] [play-state];
Code Block Loading...
3. Deep Dive into Animation Properties
| Property | Description | Default |
| animation-iteration-count | How many times to play (number or infinite). | 1 |
| animation-direction | normal, reverse, alternate (forward then back). | normal |
| animation-fill-mode | forwards (stay at end), backwards (return to start). | none |
| animation-play-state | running or paused. | running |
4. Case Study: The Rotating Circles
Let's build a complex layout of four circles that rotate as a single unit using transform-origin and absolute positioning.
5. Bridging CSS and JavaScript: Animation Events
You can use JavaScript to detect exactly when an animation starts, ends, or completes a loop. This is vital for "chaining" animations or updating the UI after a movement finishes.
Code Block Loading...
Key Takeaways
- Customization: Use intermediate percentages (25%, 50%, 75%) in
@keyframesto create non-linear, rhythmic motions. - Fill Mode: Use
animation-fill-mode: forwardsif you want the element to stay in its final state after the animation ends. - Hardware Acceleration: Like transitions, animating
transformandopacityprovides the best performance (60fps). - JS Synergy: Use
animation-play-state: pausedvia JavaScript to stop an animation when a user interacts with an element (e.g., onmouseenter). - Naming: Keep animation names descriptive (e.g.,
fadeIn,slideDown) for better code maintainability.