Elentok's Blog

About me

CSS Sprites Generator

I have been using CSS sprites a lot lately and wanted a tool to generate them automatically, so I wrote a simple python tool (using the python imaging library) to generate a single image (at the moment it just creates a simple horizontal merge of the images).

To use the tool just run the following command:

sprites-gen.py {output-file} {input-file1} {input-file2} ...

You can also set a fixed height (it will rescale every image to fit the height) using the "--fixed-height" argument and define the quality of the output image using the "--quality" argument.

You can get this tool at https://github.com/elentok/sprites-gen

What are CSS Sprites?

For those of you don't know what CSS sprites are, here is a short explanation:

CSS Sprites is a web development technique used primarily to improve performance by minimizing the amount of requests send to a web server.

Let's take for example a web site that uses 5 16x16 icons (a total of 3.8kb), to load these images the browser has to send 5 requests (the overhead of each request is usually longer than the time it takes to actually transfer the image data).

To solve this problem we create the following image (80x16 pixels):

This image will only require a single request to load (and it weighs 3.4kb which isn't a big difference but still a difference).

To use every icon in the web site we use the "background-position" CSS attribute.

For the example we will use the following HTML code:

<a href="#" class="icon" id="icon1"></a>
<a href="#" class="icon" id="icon2"></a>
<a href="#" class="icon" id="icon3"></a>
<a href="#" class="icon" id="icon4"></a>
<a href="#" class="icon" id="icon5"></a>

And the following CSS code:

.icon {
  background-image: url(sprites.png);
  width: 16px;
  height: 16px;
  display: block;

#icon1 { background-position: 0px 0px; }
#icon2 { background-position: -16px 0px; }
#icon3 { background-position: -32px 0px; }
#icon4 { background-position: -48px 0px; }
#icon5 { background-position: -64px 0px; }

Another very useful advantage of using CSS sprites is for rollover images, to avoid using javascript to preload the hover image (otherwise you will notice a lag between the moment the cursor enters the element and the moment the rollover image appears while the browser loads the image).

So, instead of using a different background image in the :hover css block you just use the "background-position" to define the offset for the rollover image.

For more information about CSS sprites I recommend the following article from "A List Apart": "CSS Sprites: Image Slicing’s Kiss of Death".

Next:Solving Coding Problems