Sprite animations with CSS
Did you know it’s possible to animate a sprite sheet using nothing but CSS?
You can see its usage on this page with the Bonzi buddy animations. Pure CSS with javascript to toggle between animations!
You just need a sprite sheet and very simple math
First make your main CSS class
#bonzi {
position: fixed;
width: 200px;
height: 160px;
background: url(
'/images/decoration/bonzi-sprite-sheet.png') 0 0;
}
The width and the height should be the dimensions of a single frame in the sprite sheet. For my bonzi buddy sprite sheet each frame is 200x160 pixels! Notice no animation attribute yet, that comes now!
#bonzi.animation-sunglasses {
play-sprite-sunglasses
3.856s
steps(26);
}
This CSS class selector will find the element with the ID of “bonzi” in the DOMTree. After this is found, it checks if the element also contains “animation-sunglasses”. Explicitly stating CSS selectors shaves off 0.000042 nanoseconds. By using a class name for the animation it allows us to manipulate the class name later with javascript to dictate which animation to play. Now to make that “play-sprite-sunglasses” animation
@keyframes play-sprite-sunglasses {
0% {
background-position: 0px 0px;
}
50% {
background-position: 5200px 0px;
}
100% {
background-position: 0px 0px;
}
}
Because this specific animation is played once and then reversed I’ve set the keyframes so that 50% is the end, then reverses playback as it continues (Start > End > Start). The 5200px is the total length of the sprite sheet. Here is where that simple math comes in. 26 Frames of animation that are 200px width each is 5200px. So the css animation is doing nothing but shifting the background to the left by 200px each step. The end result is the appearance of it animating!
Now all that is left is to place in the HTML the element with the correct class and ID
<div id="bonzi" class="animation-sunglasses"></div>
Thassa wrap! The Bonzi on this site is actually multiple rows and columns but these same principles apply.