Transitions and Animations
40 minCSS Transitions and Animations bring life to web interfaces. They provide visual feedback to user interactions and can guide attention to important elements. A **Transition** is a simple change from one state to another (e.g., hover effect), while an **Animation** is a more complex sequence of changes controlled by keyframes.
Transitions require two things: a property to change (like `background-color`) and a trigger (like `:hover`). You define the `transition-property`, `transition-duration`, and `transition-timing-function` (easing) to control how the change happens.
Animations use the `@keyframes` rule to define intermediate steps in a sequence. You can control the start (0%), end (100%), and any point in between. You then apply this animation to an element using the `animation` property.
Performance is critical. Animating properties like `transform` and `opacity` is efficient because the GPU handles them. Animating `width`, `height`, or `margin` can cause 'layout thrashing' and slow down the browser.
Key Concepts
- Transitions smooth out state changes.
- Animations allow complex, multi-step sequences.
- `@keyframes` define the animation steps.
- Timing functions (ease, linear) control speed.
- GPU-accelerated properties (transform, opacity) are best.
Learning Objectives
Master
- Creating smooth hover effects with transitions
- Defining keyframes for animations
- Controlling animation duration, delay, and iteration
- Understanding easing functions (bezier curves)
Develop
- Enhancing UX with micro-interactions
- Balancing motion design with usability
- Optimizing animations for performance
Tips
- Use `transition: all 0.3s ease;` for quick prototyping, but be specific in production.
- Keep animations short (under 300ms) for UI interactions.
- Use `will-change` sparingly to hint browsers about upcoming changes.
- Respect user preferences with `prefers-reduced-motion`.
Common Pitfalls
- Animating layout properties (width, top, left) which causes lag.
- Making animations too slow, making the UI feel sluggish.
- Overusing animations, which can be distracting or cause motion sickness.
- Not providing a fallback for older browsers (though support is good now).
Summary
- Transitions are for simple A-to-B changes.
- Animations are for complex sequences.
- Performance matters: animate transform and opacity.
- Motion should enhance, not distract.
Exercise
Create a button that changes color smoothly on hover using a transition.
button {
background-color: #4CAF50;
color: white;
transition: background-color 0.5s ease;
}
button:hover {
background-color: #45a049;
}
Exercise Tips
- Add transform to the transition: transition: background-color 0.5s, transform 0.3s;
- Try different timing functions: ease-in-out, cubic-bezier(0.4, 0, 0.2, 1).
- Create a keyframe animation for more complex effects.
- Add will-change: transform; to hint the browser about upcoming changes.