e-Zest members share technology ideas to foster digital transformation.

CSS3 sprite image animation

Written by Madhukar Kumbhar | Feb 6, 2017 6:03:32 AM

With emerging technologies and trends, CSS animations are gaining lot of popularity. Creating animated image using CSS3 is one of newest fad among the designers. The timing function available in CSS3, can be used to create sprite animations. More precisely, each sprite image is used as frame to create a continuous animation without any special easing effects. 

We can manage the animation duration using amount of key frames. Furthermore, it is a continuous animation in equal distance steps depending upon the value we set.

It is possible to create simple sprite character with any image creating tool such as Illustrator, CorelDraw or Photoshop.

To create the sprite animate, make note that every frame size is by default 100x100. But as we are creating the image using 8 frames, the image size will  become 100x800 were frame width will be 100px and whole image width would be 800px (8 frame step animation).

This is the image sprite which I have created using Photoshop

Creating animation character

We will create a class and define the width and height dimensions and mention the sprite animation character image as a background image.

.character{

  width: 100px;
  height: 100px;
  background: url('character.gif') left center;

}

Next, after defining the background image we need to create a keyframe rule to add animation to the image. So, our sprite image width is 800px and we will animate it right-to-left to final background position that is -800px.

@keyframes move{ 

 100% { background-position: -800px; }

}

Animation Timing

To move our sprite image, use play animation sequence to the selector with the time duration. This will enable our background sprite image to move quickly from left to right position. If you are willing to change the speed, then simply change the animation duration value.

.character{

animation: play 0.9s steps(8);

}

Now, we have created 8 frames to run in 0.10s duration.
Next, we will set repeating loop of animation. To do that we will have to set the animation-iteration-count to infinite.  

.character{

animation: play 0.9s steps(8) infinite;

}

Here is a complete flow of CSS3 sprite image animation 

HTML

<div class=" character"></div>

CSS

.character{
            width: 100px;
            height: 100px;
            margin: 10px auto;
            background: url('character.gif') left center;
           animation: play 0.9s steps(8) infinite;
}

@keyframes move{ 

            100% {background-position: -800px}

}

Final Output