by Daniel Davies

I'm a bit of an optimisation addict, so wishing to squeeze every last drop of performance from my blog I've tried a new technique. Around 80% of the time spent loading a webpage is downloading files, and a significant amount of downloading a file is connection overhead. Its thus key, when having your pages load quickly that you reduce the number of times your browser hits the server.

In a previous post I looked at 3 very quick ways that anyone could optimise their homepage. The following is a way for anyone with a bit of CSS knowledge to achieve further improvements.

The Theory

To reduce the number of hits to a server, it makes sense to download as much as you can in one go. Sprites do just that. You combine several smaller images in to one larger image, and using CSS you position the image in to the right place, displaying the right bits. A classic example is a rollover link. Lets say you have a rollover link that's 20 pixels high. You create your sprite with the top 20 pixels as the link in its regular state, and then 20 pixels, within the same image, at the bottom. Using CSS you simply reveal a different part of the image when it is hovered.

An Example

Okay, so here's a sprite I'm using on this site. Take a look at the footer; there are a number of links to various other profiles I have. On each link I've got a little icon that is 16x16 pixels that relates to the site in question. Rather than hitting the server 5 times to download five 16x16 icons, I combined all of the icons in to one image. 5 x 16 is 80, so my canvas must but 16x80 pixels.

Favicon Sprite

To Position these you just need to use the background-position property in CSS. Each time I need to move the image up 16 pixels, so its quite a simple bit of code.

li.profile_sprite {
    list-style-type: none;
    padding: 0px 0 0 20px;
    float: left;
    margin-right: 10px;
    background-image: url('../images/profile_sprite.gif');
    background-repeat: no-repeat;
}

li#twitter {
    background-position: 0px 0px;
}

li#flickr {
    background-position: 0 -16px;
}

li#technorati {
    background-position: 0 -32px;
}

li#facebook {
    background-position: 0 -48px;
}

li#delicious {
    background-position: 0 -64px;
}

And then its done! You can take this technique as far as need be, even putting all your background images in to a single image file, and using the background-position and background-repeat properties position them where you need.

Talk about Optimisation Through CSS Sprites

No comments yet! Why not be the first?

Contact Daniel…

Request a Quote