Understanding CSS Sprite Animation
CSS sprites combine multiple animation frames into a single image file. By changing the
background-position over time using CSS @keyframes, we can create
smooth character animations. Our sprite sheet (sprites.png) contains 6 frames
of a running character (465×134px total, each frame is ~77.5px wide).
💡 Tip: View sprites.png to see all 6 running frames.
Task Instructions
- Style
.sprite-container:- Set
display: flex,justify-content: center,align-items: center - Set
min-height: 200px - Add gradient background:
linear-gradient(135deg, #667eea 0%, #764ba2 100%) - Add
border-radius: 12pxandpadding: 40px
- Set
- Style
.running-character:- Set
width: 76pxandheight: 134px - Set
background-image: url('images/sprites.png') - Set
background-repeat: no-repeat - Add
overflow: hidden(clips to show only one frame) - Add
animation: run 0.8s steps(1) infinite(steps(1) prevents smooth sliding)
- Set
- Create
@keyframes runanimation:- At
0%:background-position: 0 0 - At
16.66%:background-position: -78px 0 - At
33.33%:background-position: -156px 0 - At
50%:background-position: -234px 0 - At
66.66%:background-position: -312px 0 - At
83.33%:background-position: -390px 0 - At
100%:background-position: 0 0
- At
🔧 Fine-Tuning Tips
If frames don't align perfectly, adjust positions by ±1-2px:
- Check if the character's feet stay at the same vertical level
- Adjust each keyframe's X position until smooth
- Each frame is approximately 76px apart
Key Learning Points:
- CSS Animation:
@keyframesdefines how the background position changes over time - steps(1) Function: Makes animation jump to each frame instantly, no smooth sliding between frames
- Manual Positioning: Each frame is positioned individually for precise control (works with uneven sprite sheets!)
- Animation Speed: 0.8 seconds per cycle creates a natural running motion
- Performance: 1 sprite sheet loads faster than 6 separate images
- infinite: Makes the animation loop continuously
🎬 Animation Breakdown: The steps(1) function makes the animation jump from frame to frame
instantly (no smooth sliding). Each keyframe percentage (0%, 16.66%, 33.33%, etc.) displays one specific frame by
shifting the background position. This creates crisp, frame-by-frame animation like a cartoon!