Using CSS sprites is a great way to speed up your web pages and web applications. The concept is simple: bundle up all your icons into one image and use the background-position property to display the correct icon. By doing this you avoid having to download multiple image files and minimize your HTTP requests. Using sprites is especially useful for rollovers since it avoids having to preload images altogether. An example of a CSS sprite is shown below.

sprites

The sprite above has all the icons laid out in a grid with the icons 20px apart. If I wanted to show the Linux penguin in a div I would use to following style:


.penguin {
background-image: url(sprites.png);
background-position:  -80px 0px;
}

This style rule places a background-image at a position that’s -80 pixels from the left and 0 pixels from the top. It’s simple enough with a small graphic like the one above, but when you begin using more complex sprites you need to begin doing some math, and being a designer true to my creed, I hate math. Fortunately, using LESS makes things much easier. All you have to do is setup the width and height of your grid cells like this.


@xwidth: 20px; //cell width
@ywidth: 20px; //cell height

Then all you need to know is the column and the row for your icon and set the background position like this:


background-position: @xwidth*-5 @ywidth*0; //remember the first column or row is 0

The image below illustrates the rows and columns of a sprite. the background-position property always uses a negative number when positioning a sprite.

sprites-grid

An alternative method is to set your icons in the beginning of the document like this:


@xwidth: 20px; //cell width
@ywidth: 20px; //cell height
@penguin: @xwidth*-5 @ywidth *0;

and then just call the css as follows:


background-position: @penguin;

Either way the result is the same, and as our good symfony friends from France would say, Voila! CSS sprites made simple.

Special thanks to Mark James for his FamFamFam icons.