Introduction to CSS Animations
Animations and transitions bring life to web pages, enhancing user experience by providing visual feedback, guiding attention, and creating engaging interfaces. CSS offers powerful, performant ways to animate elements without JavaScript.Transitions
Simple animations between two states, triggered by changes like hover or class toggles.
Keyframe Animations
Complex, multi-step animations with precise control over the animation sequence.
Why Use CSS for Animations?
Performance
CSS animations are optimized by browsers and often hardware-accelerated, making them more performant than JavaScript animations for many use cases.
Simplicity
CSS animations require less code than JavaScript alternatives and are easier to implement for common animation patterns.
Declarative
CSS animations are declarative, meaning you describe what should happen rather than how it should happen, making them easier to understand and maintain.
Progressive Enhancement
CSS animations can be added as an enhancement without breaking functionality for users with animations disabled or unsupported browsers.
CSS Transitions
Transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes to take place over a period of time.Basic Syntax
Transition Properties
| Property | Description | Example Values |
|---|---|---|
transition-property | Specifies which CSS properties should be animated | all, opacity, transform, width, height |
transition-duration | Defines how long the transition takes to complete | 0.3s, 300ms, 2s |
transition-timing-function | Specifies the speed curve of the transition | ease, linear, ease-in, ease-out, ease-in-out, cubic-bezier(0.1, 0.7, 1.0, 0.1) |
transition-delay | Defines when the transition will start | 0s, 0.5s, 500ms |
transition (shorthand) | Combines all transition properties into one declaration | all 0.3s ease 0s, opacity 0.5s linear |
Animatable Properties
Not all CSS properties can be transitioned. Here are some commonly animated properties:Layout Properties
Layout Properties
width,heightmargin,paddingtop,right,bottom,leftborder-width
Animating layout properties can trigger browser reflow, which can be expensive for performance. Prefer using
transform when possible.Visual Properties
Visual Properties
opacitycolor,background-colorbox-shadow,text-shadowborder-color,outline-colorvisibility
Transform Properties
Transform Properties
transform: translate()transform: scale()transform: rotate()transform: skew()
Transforms are highly optimized by browsers and are the preferred way to animate position, size, and rotation.
Filter Properties
Filter Properties
filter: blur()filter: brightness()filter: contrast()filter: grayscale()filter: hue-rotate()filter: invert()filter: opacity()filter: saturate()filter: sepia()
Timing Functions
Timing functions control the pace of the animation, making it more natural and engaging.
You can visualize and create custom cubic-bezier curves using tools like cubic-bezier.com.
Practical Examples
Button Hover Effect
Card Expansion
Navigation Menu
CSS Keyframe Animations
Keyframe animations provide more control than transitions, allowing you to define multiple states throughout the animation sequence.Basic Syntax
Animation Properties
| Property | Description | Example Values |
|---|---|---|
animation-name | Specifies the name of the @keyframes rule | slide-in, fade-out, pulse |
animation-duration | Defines how long the animation takes to complete one cycle | 1s, 500ms, 2.5s |
animation-timing-function | Specifies the speed curve of the animation | ease, linear, ease-in, ease-out, ease-in-out, cubic-bezier(0.1, 0.7, 1.0, 0.1) |
animation-delay | Defines when the animation will start | 0s, 1s, -0.5s (negative values start the animation partway through) |
animation-iteration-count | Specifies how many times the animation should run | 1, 3, infinite |
animation-direction | Defines whether the animation should play forward, backward, or alternate | normal, reverse, alternate, alternate-reverse |
animation-fill-mode | Specifies what values are applied before/after the animation | none, forwards, backwards, both |
animation-play-state | Specifies whether the animation is running or paused | running, paused |
animation (shorthand) | Combines all animation properties into one declaration | slide-in 1s ease-out 0s 1 normal forwards |
Keyframe Syntax
Keyframes define the stages and styles of the animation sequence.You can define as many keyframe stages as needed, and you don’t need to include every property in every stage. CSS will interpolate between defined keyframes.
Animation Fill Mode
Theanimation-fill-mode property determines what happens before the animation starts and after it ends.
| Value | Before Animation | After Animation |
|---|---|---|
none (default) | Element displays in its normal state | Element returns to its normal state |
forwards | Element displays in its normal state | Element retains the computed values set by the last keyframe |
backwards | Element displays the computed values set by the first keyframe | Element returns to its normal state |
both | Element displays the computed values set by the first keyframe | Element retains the computed values set by the last keyframe |
Practical Examples
Loading Spinner
Pulsing Effect
Staggered Animation
Advanced Animation Techniques
Multiple Animations
You can apply multiple animations to a single element by separating them with commas.Animating Along a Path
With CSSoffset-path (part of the Motion Path Module), you can animate elements along a defined path.
Scroll-Triggered Animations
You can trigger animations when elements enter the viewport using the Intersection Observer API with JavaScript.CSS Variables for Dynamic Animations
CSS Custom Properties (variables) can make animations more dynamic and configurable.Animating SVG
SVG elements can be animated with CSS, offering unique possibilities for graphics animation.Performance Optimization
Animations can impact performance if not implemented carefully. Here are some best practices:Use Hardware-Accelerated Properties
Some CSS properties are optimized for animation and can be hardware-accelerated:transformopacityfilter
Promote Elements to Their Own Layer
You can force an element onto its own GPU layer withwill-change or transform: translateZ(0).
Reduce Paint Areas
Limit the size of animated elements and usecontain: paint to isolate their paint areas.
Avoid Animating Expensive Properties
Some properties are particularly expensive to animate because they trigger layout recalculations:width,heighttop,right,bottom,leftmargin,paddingfont-sizeposition
transform equivalents:
Animation Accessibility
Animations can enhance user experience but may cause issues for some users, particularly those with vestibular disorders or motion sensitivity.Respect User Preferences
Theprefers-reduced-motion media query allows you to provide alternative animations or disable them based on user system preferences.
Avoid Flashing Content
Rapid flashing or strobing effects can trigger seizures in people with photosensitive epilepsy. Avoid animations with:- Flashing more than 3 times per second
- Large areas of flashing content
- High contrast flashing
Provide Controls
For significant animations, provide users with controls to pause, stop, or disable animations.Browser Compatibility
Modern browsers have good support for CSS animations and transitions, but there are some considerations for older browsers.Vendor Prefixes
For older browsers, you might need vendor prefixes. However, most modern browsers no longer require them for animations.Consider using a tool like Autoprefixer to automatically add necessary vendor prefixes based on your browser support requirements.
Feature Detection
You can use feature detection to provide fallbacks for browsers that don’t support certain animation features.Common Animation Patterns
Here are some reusable animation patterns for common UI elements:Fade In
Slide In
Bounce
Pulse
Shake
Rotate
Flip
Animation Libraries
While CSS animations are powerful, animation libraries can provide additional features and simplify complex animations.Popular CSS Animation Libraries
Animate.css
A library of ready-to-use, cross-browser animations for use in your web projects.Animate.css Documentation
Magic Animations
Hover.css
CSShake
JavaScript Animation Libraries
For more complex animations or when you need programmatic control, JavaScript libraries can be helpful:GSAP (GreenSock Animation Platform)
Anime.js
Motion One
A new animation library, built on the Web Animations API for high performance.Motion One Documentation
Lottie
Conclusion
CSS animations and transitions provide powerful tools for creating engaging, interactive web experiences. By understanding the fundamentals and following best practices, you can create smooth, performant animations that enhance your user interface without sacrificing accessibility or performance. Key takeaways:- Use transitions for simple state changes and keyframe animations for more complex sequences
- Prefer animating
transformandopacityfor better performance - Consider accessibility with
prefers-reduced-motionand animation controls - Optimize animations for performance by minimizing repaints and reflows
- Use animation libraries when you need more complex effects or better browser support
Resources
Documentation
Tools
Further Learning
- CSS Animation Rocks
- Web Animation Workshops
- Animation at Work by Rachel Nabors