views:

43

answers:

3

I am trying to be more Zen in my CSS, and also to reduce the load on my server. I have heard and sort of seen a technique where I can use a background image and an offset value to allow me to download all my little icon images in one single image, and use CSS to display the right image. However, I am a little confused how to do this correctly. Specifically, if I have a 16x16 image, 48 pixels along in my big image, called img.png, I want something like this:

<img style="background-image: url('img.png'); background-position: 48px" />

(Obviously taking the style out into CSS, but inline here for illustrative purposes.)

However, img ignores the offset. If I used something like a span I am not sure exactly how to set the width of the span (in fact I tried, and it seemed to ignore width.)

Any help would be appreciated.

+1  A: 

You're thinking of CSS sprites. This article should point you in the right direction.

Hooray Im Helping
+2  A: 

You would use a different tag than an img tag, you need to specify the size of it, and the background position should be negative. You can use a div tag for example, as it's a block tag by default so that you can specify a size for it:

<div style="width: 16px; height: 16px; background: url('img.png') -48px;"></div>

If you only specify one offset, its horizontal position and the vertical position is zero. If it's a vertical offset you have to specify both a horizontal and vertical offset:

<div style="width: 16px; height: 16px; background: url('img.png') 0 -48px;"></div>
Guffa
+1  A: 

you can use this tool to generate sprite images and also the tool takes care generating the css for you

Vinay B R