CSS Animations
advancedPart of Advanced CSS
Theory
CSS animations bring web pages to life by smoothly changing property values over time. They range from simple hover effects to complex multi-step sequences — all without JavaScript.
CSS Transitions
Transitions animate property changes between two states. They require a trigger (like :hover) and define how the change happens:
.button {
background: #3498db;
transition: background 0.3s ease, transform 0.2s ease;
}
.button:hover {
background: #2980b9;
transform: translateY(-2px);
}Transition properties: transition-property, transition-duration, transition-timing-function (ease, linear, ease-in, ease-out, cubic-bezier()), and transition-delay.
CSS Transforms
The transform property modifies an element's shape and position without affecting the layout. Common functions:
translate(x, y)— moves an elementscale(x, y)— resizes (1 = original)rotate(angle)— rotates (deg, rad, turn)skew(x, y)— skews along axestransform-origin— sets the pivot point (default center)
Combine multiple transforms: transform: scale(1.1) rotate(5deg) translateX(10px);
Keyframe Animations
The @keyframes rule defines multi-step animations with percentage stages:
@keyframes slideIn {
0% { transform: translateX(-100%); opacity: 0; }
50% { transform: translateX(10%); }
100% { transform: translateX(0); opacity: 1; }
}
.element {
animation: slideIn 0.8s ease-out forwards;
}Animation Properties
animation-name— @keyframes nameanimation-duration— how long one cycle takesanimation-timing-function— speed curveanimation-delay— delay before startinganimation-iteration-count— number of cycles (1,3,infinite)animation-direction—normal,reverse,alternate,alternate-reverseanimation-fill-mode—none,forwards,backwards,bothanimation-play-state—running,paused
Performance Tips
Animating certain properties triggers layout recalculations and repaints, which hurts performance. For smooth 60fps animations:
- Prefer
transformandopacity— these only trigger compositing - Avoid animating
width,height,top,left,margin,padding— these trigger layout - Use
will-change: transform, opacityon animated elements - Use
transform: translate()instead oftop/left - Consider
prefers-reduced-motion: reducefor accessibility
Browser DevTools can show you which properties trigger layout vs compositing. Look for the 'Rendering' or 'Performance' tab to record and analyze animation performance.
Practical Examples
Exercises
Create a Staggered Fade-In Animation
Build a page with a list of 4 items that fade in and slide up one after another using @keyframes and animation-delay. Each item should appear 0.2s after the previous one. Also add a spinning loading indicator at the top.
Expected Output:
A rotating spinner at the top. Below, 4 items sequentially animate in: Item 1 appears first, then Item 2 (0.2s delay), Item 3 (0.4s), and Item 4 (0.6s). Items slide up and fade in.