Building Sprites for Easy CSS

We’re building an image sprite for 16x16 icons. Adjust numbers accordingly if using different-sized icons.

I’ve used sprites for a while now, though generally, they’re a pain to setup — especially the CSS positioning. Finally I wised up and figured out a perfect way to align the icons to easily reuse the same CSS positioning on all projects.

In Photoshop, create a new document with the dimentions of 16x2050. This is my standard sprite image size, though often it gets cropped when I’m finished.

The maximum size for decoded GIF, PNG, and TIFF images is 3 megapixels for devices with less than 256 MB RAM and 5 megapixels for devices with greater or equal than 256 MB RAM.

That is, ensure that width * height ≤ 3 * 1024 * 1024 for devices with less than 256 MB RAM. Note that the decoded size is far larger than the encoded size of an image.

iOS Developer Documentation

Adjust your document’s grid in Edit > Preferences > Guides, Grid & Slices. Set your Gridline to 50 pixels with 1 subdivision. This setup makes it easy to space our images in 50px increments, making our CSS much easier.

Pull all your icons in the document and align them by snapping the top of each icon to each grid line. Be sure to leave the top grid block blank — this is in case the background isn’t properly positioned for some reason, you won’t have a screen full of links with the same exact icon.

Your images might need to drop down a pixel or two for perfect alignment.  For me, I set the first icon at 52px. Now look how easy our CSS is to write:

Example of Clean Sprite CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
.icon                  {background:url(images/icons.png) 0 0 no-repeat; padding-left:20px;}
a.icon                 {font-size:14px; line-height:16px;}
.icon.errorx           {background-position:0px -50px;}
.icon.alert            {background-position:0px -100px;}
.icon.delete           {background-position:0px -150px;}
.icon.info             {background-position:0px -200px;}
.icon.help             {background-position:0px -250px;}
...
.icon.customer         {background-position:0px -1850px;}
.icon.sort-active      {background-position:0px -1900px;}
.icon.sort             {background-position:0px -1950px;}
.icon.sort-up          {background-position:0px -2000px;}
.icon.sort-down        {background-position:0px -2050px;}

This setup also gives you some wiggle room about each icon, so in many cases you can forgo the 16x16 span and just use the sprite as a background of the actual element.