Why use a sprite sheet rather than individual images?

Niet the Dark Absol picture Niet the Dark Absol · Nov 8, 2011 · Viewed 18k times · Source

One thing I have noticed on some sites is that they use one BIIIIIIIG image containing lots of little images, then use CSS background-position to define the coordinates of each image, rather than use individual images.

Here's where I'm at:

Cons for using big sprite sheet

  • Need to load a large image to just display even one small image
  • Need to write (or generate) a long stylesheet with a class for each image
  • Cluttering CSS with lots of class definitions may impact performance
  • If one image changes (or another is added), cache problems may be encountered both on the image and the CSS associated with it
  • Requires a <div> with proper styling (display: inline-block; width: 32px; height: 32px; background-image: url('spritesheet.png');) which adds yet another class to the mix.
  • Many more that I can't remember now I'm typing them.

Pros for using big sprite sheet

  • ... Erm... none yet.

In fact the only thing that comes close to a pro here is that when I cut up the sheet into individual images the resulting folder took up 3Mb on disk (due to each file being <100 bytes and my allocation size being 4k). The actual files themselves come out less than half the size of the sheet and CSS, so even with the overhead of an HTTP request there is a significant space saving.

Basically, my question is: Does anyone have ANY pros for using a big sheet over individual images?

Answer

Rich Bradshaw picture Rich Bradshaw · Nov 8, 2011

The aim is to reduce HTTP requests. In addition, sometimes the compressed sprite will weigh less than the original images.

Recently I had a website with a lot of transparent gradients (white to trans, grey to trans) and some black and white on transparent images. By putting them all in a sprite and reducing the colors in the png to 8 I could get the sprite to be smaller in filesize than the original images (just... it was about a 0.5% saving). By reducing the number of HTTP requests from 10 to 1 though meant the site loaded faster (if measuring time from first connection to all data transferred).

In that case, a measurable increase was found.

I agree though that it's possible to mess things up and to end up with a larger sprite than needed, especially if you aren't using PNG compression.

Note two years after posting this – if you are using SSL, you should look into SPDY (my note in a further two years will mention HTTP 2.0 instead of SPDY!). SPDY negates the benefits of spriting.