Hi I'm Colin Ainscough, and I am a print and digital guy based in Lancashire


May 15, 2009 0 9:51 pm

CSS sprites – What they are, and how to use them?

This is short article to briefly explain what sprites are and how you can implement them into you CSS designs.

CSS sprites are the combination of many images into one large image, each individual image is then moved using background position to be visible within each container; this process is extremely usefull in navigation menus where you would want two or three button image states (This method also nicely replaces the need for unnecessary javascript libraries).

What you will gain from using CSS sprites is better performance from you site as it needs to make less HTTP image requests which will ease the load on your pages.

A simple example:

Firstly, create an image 250px wide and 100px deep, within the image area create two button states with slightly different styles so that each state will be clear to the user (As in the example below).  Save the image as a JPEG ready to use in the CSS.

The CSS:

Then place the following CSS into the head of your document;  this will create the display area for the sprite while the background position will display the first button state.

ul.menu { list-style:none; padding:0; margin:0; }

ul.menu li a { list-style:none; display:block; width: 250px; height:50px; background:url(btn_eg.jpg) no-repeat; background-position: 0 0; }

Next we need to add the hover state, this will simply move the image up withing the same container when the mouse is over the button.  To include the hover state simply add the following CSS after the main menu code.

ul.menu li a:hover { background-position: 0 -50px; }

The HTML:

Finally reference your button in the body as you would normally with the following HTML:

<ul class=”menu”>
<li><a href=”http://nasarik.com”></a></li>
</ul>

To see the final example click here

Overview

And you are done, a simple an effective way to start using CSS sprites in your pages. I have added two links to more in-depth articles on the subject of sprites below enjoy.

CSS Sprites: What They Are, Why They’re Cool, and How To Use Them
The Mystery Of CSS Sprites: Techniques, Tools And Tutorials


Tags:, , , , , , , ,

Categorised in: css, tutorials

This post was written by nasarik

Comments are closed here.