pexichdu pexichdu - 5 months ago 19
CSS Question

Make CSS sprite animation work

Im new to css animation, so I got this sequence movements picture online and want to make it walks. I follow a tutorial but it doesn't work in this case. I'm trying to make it moves. I don't know how to properly do that so I start with the first row of image. Its dimensions are 832x228.

and this is CSS code:



.sprite {
width: 130px;
height: 130px;
display: block;
background: transparent url(http://i.stack.imgur.com/UOPXb.png) 0 0 no-repeat;
animation: walker 1s steps(8) infinite;
}
@keyframes walker {
0% {
background-position: 0 0;
}
100% {
background-position: 832px 0px;
}
}

<div class="sprite"></div>




Answer

You are on the right path but the background-position is wrong within the keyframes. Sprite images should move from the right to the left in order to produce a moving animation and so the background position should go from 0 0 to -832px 0.

.sprite {
  width: 114px;
  height: 114px;
  display: block;
  background: transparent url(http://i.stack.imgur.com/UOPXb.png) 0 0 no-repeat;
  animation: walker 1s steps(8) infinite;
  /* image size is 832x228, so height is set as half of it */
}
@keyframes walker {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: -832px 0px;
  }
}
<div class='sprite'></div>


As mentioned in Robert C's answer, this will still not get the second row of images to show up. This is because the Y part of background-position doesn't change within the keyframes. The below snippet kindly contributed by Mishko Vladimir is one way to get them to display but problem is that if the no. of steps is increased to 16 (so as to show all sprites) then the animation doesn't work properly anymore.

Also, there will be a blink at the point where Y position changes. So, my recommendation would be to put all 16 sprites in the same row instead of two.

.sprite {
  width: 114px;
  height: 114px;
  display: block;
  background: transparent url(http://i.stack.imgur.com/UOPXb.png) 0 0 no-repeat;
  animation: walker 1s steps(8) infinite;
  /*832x228*/
}
@keyframes walker {
  0% {
    background-position: 0 0;
  }
  50% {
    background-position: -832px 0px;
  }
  51% {
    background-position: 0 -114px;
  }
  100% {
    background-position: -832px -114px;
  }
}
<div class='sprite'></div>

Comments