CSS Sprites (using fewer images)

(This post was originally published in 2006. I’ve just moved it from my old Wordpress blog to Tumblr.)

Image rollovers are usually composed of two individual images; one for the default state and one for when the mouse is hovered over the image or link. However, it bears some advantages to use a single image by taking advantage of CSS background image offsets. I’ll start by describing how a rollover for an anchor is typically done.

The HTML code could look like something like this:

<a href="#" id="yaprak">&nbsp;</a>

The associated CSS would then have items like:

a#yaprak {
    width: 64px;
    height: 64px;
    background-image: url(yaprak_bw.png);
    display: block;
    text-decoration: none;
}

a#yaprak:hover {
    background-image: url(yaprak_color.png);
}

Two individual images for the two states would have to be uploaded to the server and they would look like this:

Finally, the end result would be:

The default image that is visible to the user is the black & white yaprak_bw.png and when you hover over the image, it’s replaced by yaprak_color.png with its full-color glory. However, if this is a user’s initial visit to the website and therefore the color image hasn’t already been cached, there may be a user-perceivable delay in switching to the color image. The net annoyance will depend on factors like the user’s connection speed, the load on the web server and most importantly, the attentiveness of the user. A couple of methods can be applied to pre-load alternate images to avoid the perceived latency but I will advocate for something else: don’t use separate alternate images in the first place. You can use a single image where the two rollover images are flush with each other, side by side or one on top of another. Here’s how:

The HTML code is the same. The CSS this time has:

a#yaprak {
    width: 64px;
    height: 64px;
    background-image: url(yaprak_bw_color.png);
    display: block;
    text-decoration: none;
}

a#yaprak:hover {
    background-position: 64px 0;
}

There’s only a single image:

The end result is:

Using fewer images might marginally speed up the load times for your website while also decreasing the load on your web server. Another scant advantage is that you’d have less images to worry about maintaining and uploading to your web server.