CSS Animate Background Image

Animation Keyframes vs Transition

Animation Keyframe

Transition background-position


There are two approaches to animating a sprite on hover with CSS

There is the animation keyframe approach, and there is a property of CSS transition specifically for background-position. It's as simple as:

.banner-transition:hover{
  background-position:0 -533px;
  transition:background-position 1s ease;
}

It's worth reading Paul Irish's thoughts on anything. Why Moving Elements With Translate() Is Better Than Pos:abs Top/left is an article I reference frequently when I'm trying to remember which approach to use when using CSS animations.

Use CSS keyframe animation or CSS transitions, if at all possible. The browser can optimize painting and compositing bigtime here.

As far as I know CSS translate doesn't affect background-position which left the transition and animation keyframe approach.

It's easy to do a quick test using the timeline tools. I recorded the animation twice for each - The difference is minimal but visually, and from the timeline it looks like using animation keyframe is slightly smoother.

Don't forget your browser prefixes, this example uses -webkit- prefixes only. Here is a working example of the code on codepen.


Animation Keyframe

Avg. - 7.00ms, Standard Deviation - 6.481ms

/* CSS Animation Keyframe Approach */
.banner-keyframe{
  background: url(http://s.cdpn.io/5847/background-image-sprite.jpg) no-repeat 0 0;
  height:533px;
  width:800px;
  margin:0 auto;
}
.banner-keyframe:hover{
  -webkit-animation: background-ani 1s ease normal;
  background-position:0 -533px;
}
/* The Animation 0 - 100% */
@-webkit-keyframes background-ani {
  from{
    background-position:0 0;
  }
  to{
    background-position:0 -533px;
  }
  
}	

Transition

Avg. - 9.67ms, Standard Deviation - 7.134ms

/* CSS Transition background-position Approach */
.banner-transition{
  background: url(http://s.cdpn.io/5847/background-image-sprite.jpg) no-repeat 0 0;
  height:533px;
  width:800px;
  margin:0 auto;
}
.banner-transition:hover{
  background-position:0 -533px;
  -webkit-transition:background-position 1s ease;
}

The Sprite

Animate background-position from top to bottom with a height of half the image to show only one.