What IS A CSS Button Sprite?

Let me start off by explaining what an image sprite is. A sprite is basically one larger image that is made up of many smaller images. The idea of sprites is that you only need to load one image and then apply it to a smaller div or A tag so only a portion of the large image shows. Then depending on the background position of the image, you will only see one of the smaller images. This tutorial will be useful if you want to create button sprites, menu sprites, sprite animations or any other type of sprites. If you would like to see an example on using these sprites to create a sprite animation, check out the sprite animation tutorial.

CSS Button Sprite Example

Below is showing you a css button sprite. This article will show you how to create this button sprite.

Above is the finished example of what this tutorial will show you. Mouse over this sprite button image and see how it works and bear in mind that we are only using one image to create the rollover effect. The button is actually an A (anchor) tag that has a height 32px which is half of the image sprite height. This way, only the top half of the image shows which is the up state part of the image.

Why should you use css sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Button Sprite

Above is the css button sprite image I made to create the above button sprite with it’s two states. Normal state when it is untouched and second state is the hover state for when we mouse over it. Notice that the one image contains both up and down states and then as we mouse over it, we use css to adjust the background position of the image sprite to make it appear that the button state is changing.

Now for the code to get this all working

CSS Code

<style>
/* css to style the button */
#rollover {
background: #FFF url("images/sprite.png");
width: 180px;
height: 32px;
display: block; /* can use inline-block instead of block */
}
/* hover is trigger when we mouse over the A (anchor) tag and adjust the
background position of the sprite to make it appear the button is down */
#rollover:hover {
background-position: 0 -32px;
}
</style>

HTML Code

Next the html A (anchor) tag we apply the rollover button style to.

<a href="#-" id="rollover"> </a>

Now when we mouse over, it will appear that the button is changing states. Image sprites aren’t only for buttons, but can be used for rollover menus, animations, or anything that has multiple display states.