Site icon Treehouse Blog

How to Create a CSS Sprite Animation With steps()

Adobe Illustrator artboards

There’s a little-known timing function in CSS animations that lets us break an animation into segments––or steps––instead of running it as one continuous animation from start to finish. This function is useful for creating sprite animation because we’re able to precisely display each sprite image as a frame without any easing effects in between.

How to Animate Sprite Sheet Images With the steps() Function

With steps() we’re able to control the number of keyframes rendered in an animation’s duration; it progresses the animation in equidistant steps based on the value we set. Knowing this, let’s use steps() to create a simple character sprite sheet animation.

Related Reading: CSS vs. HTML: What’s the Difference?

I used Illustrator artboards to create each animation frame as a separate 190×240 image, then took advantage of Compass’ spriting feature to quickly generate a horizontal sprite sheet containing all the exported images.

The final animation sprite sheet

Creating the CSS Sprite Animation

To animate our monster character, we’ll first create a CSS rule where we define the width and height dimensions and display the main sprite sheet as a background image.

.monster {
  width: 190px;
  height: 240px;
  background: url('monster-sprite.png') left center;
}

Next, we need to create a keyframe rule that animates the background position of the sprite sheet. The sprite sheet’s total width is 1900px, so let’s animate it right-to-left by giving it a final background position of -1900px.

@keyframes play {
   100% { background-position: -1900px; }
}

Running the Sprite Sheet Animation

At this point, when we bind the play animation sequence to the .monster selector with a duration of .8s, we see the background position of our sprite sheet quickly animating from left to right.

.monster {
  ...
  animation: play 0.8s;
}

To achieve the desired frame-by-frame animation effect, we’ll need to include the steps() timing function in the animation value. Since the sprite sheet contains 10 image sprites, we can say that it’s made up of 10 frames––or steps. So let’s define 10 steps in our animation sequence:

.monster {
  ...
  animation: play 0.8s steps(10);
}

Now the animation will run 10 frames in its .8s duration – it uses the background position animation to run through each sprite image as a step.

Finally, if we set animation-iteration-count to infinite, it will render a repeating loop of the animation.

.monster {
  ...
  animation: play 0.8s steps(10) infinite;
}

To change the speed of the CSS sprite animation, simply change the animation-duration value. Here’s the final sprite sheet animation sequence posted on CodePen:

See the Pen CSS Animation with steps() by Guil H (@Guilh) on CodePen.

Show us what you can create with steps() in the comments section. Or start learning CSS on Treehouse today!

Exit mobile version