rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

How to use CSS Sprites

Remember back in the days when we had to pre-load images using JavaScript because we used different images when we "onmouseover" menus? Well that time is long gone now. That can be easily completed by using only CSS!

The technique, also commonly called Sprites, is simply to use one big (optimized) image that stores multiples images positioned next to each other. Then, by using CSS, you set the position of where the image is in the background-position property.

Why using Sprites?

What do you have to keep in mind when you use sprites?

Here's a simple example using this website image

We will create a "Digg" button.

Using the site image, we find out the location of the digg button. book of zeus css sprites images

Let's build the CSS:

The idea is to update the X and Y position based on the location of where the image is located. The easy part with this, is you know right away if the position you entered is good. For example:

#sample a {
  height:32px; width: 32px;display:inline-block;
#sampleDigg {
  background: url('/download/boz.png') no-repeat -616px -251px;
  display: block;
  border: solid 1px #ddd;
#sampleDiggWrong {
  background: url('/download/boz.png') no-repeat -584px -205px;
  display: block;
  border: solid 1px #ddd;

Why negative coordinates?

Think sprites images as an X/Y Graph. The top left corner is 0,0. Therefore, if you move the picture to the right and bottom, you are moving the images to the left and up. Which means updated the coordinates negatively.

Let's build the HTML

<a href="#link" id="sampleDigg"></a>
<br />
<a href="#link" id="sampleDiggWrong"></a>

Here's the output

As you can see, the coordinates on the second image are wrong. Therefore, easy see visually see errors on the page.

Posterize your image

A simple trick most designer do when creating a CSS Sprite image, is to posterize it. Posterization of an image entails conversion of a continuous gradation of tone to several regions of fewer tones, with abrupt changes from one tone to another.. This can benefit you to get a smaller image without loosing quality.


At first, Sprites will require a little of patience. Don't worry, you will get use to it.