Posted 01.03.2011

Posted 01.03.2011

Several weeks ago, I posted a tweet about CSS Sprites. — I thought I’d go into a little more detail than 140 characters.

In layman’s terms, what are CSS Sprites?

Let me give you a metaphor: I have a stack of pictures I want you to look at it. You come to me, I give you 1 picture. You take it, look at it, and then come back to me for the next picture. This is fine. It works. It gets the job done. But, let’s be honest, after the 4th or 5th time, definitely the 23rd time, you’re tired of coming and going.

Enter CSS Sprites.

Instead of giving you one picture each time you came, what if, I just gave you one large sheet that had all the pictures on it. I’m putting the responsibility on you to handle the large sheet and focus on each individual picture as you’re ready for it. A larger sheet, yes, but not as much coming and going.

CSS Sprites = same thing.

The Real World (not MTV)

When you come to my website, instead of giving you 10, 20, 30 little icon images, I’ll give you 1 large image that has all of those icons on it.

You may be surprised to discover, but this is very popular technique that sites like Amazon and Apple and YouTube implement. Check it out:

In case you’re wondering, I do have links plugged into the href parameter. I just removed them for demonstration purposes.

Then, in the CSS, I have 7 different classes. 1 main class that defines all the properties, like padding, float, etc (another main class that defines hover) and 5 different classes that define the positioning for each icon.

Notice the background-position has a negative value. That’s because we’re essentially sliding the background up. Essentially, what we’ve created looks like this:

The grayed out parts of the background image, you can’t see because we’ve set the height to 22 pixels.

Sweet! This works great…until….

My Dilemma

As I pointed out earlier, you can’t see the grayed out parts of the background image because we’ve set the height to 22 pixels. Well, what happens when you have content that needs to be able to grow vertically? If you change height to min-height, you’re able to see the stacked icons. Not what I want!

Chris (yes, we’re on a first name basis) does a fantastic job of explaining everything in his blog post. But, essentially, instead of using a background image on a container, you use the CSS clip property on an image.