CSS Sprites: What They Are, Why They’re Cool, and How To Use Them (Part 2)

Pesan Sponsor Kami

OK. So how is it done?

I thought you would never ask. Let’s start by showing the BEFORE example. Notice in the CSS below how the anchor tag does not get a background-image, but each individual class does.

#nav li a {background:none no-repeat left center}
#nav li a.item1 {background-image:url('../img/image1.gif')}
#nav li a:hover.item1 {background-image:url('../img/image1_over.gif')}
#nav li a.item2 {background-image:url('../img/image2.gif')}
#nav li a:hover.item2 {background-image:url('../img/image2_over.gif')}
...

example1before.png

Using CSS Sprites, we can really lighten this example up. Instead of having ten separate images for the buttons (five default states and five rollover states), we can literally combine all of them into one big long image. I won’t go into great detail about how this is done, I’ll just give you a basic walkthrough. Create a new image that is as wide as your widest image and and as tall as the combined height of all your images plus X pixels, where X is the number of images you have. Now place you images into this new image, left aligned, one on top of the other with one pixel of white space in between.

Now check out the AFTER example. Notice in the CSS that there is a single background-image applied to the anchor element itself, and the unique classes merely shift the background position with negative Y coordinates.

#nav li a {background-image:url('../img/image_nav.gif')}
#nav li a.item1 {background-position:0px 0px}
#nav li a:hover.item1 {background-position:0px -72px}
#nav li a.item2 {background-position:0px -143px;}
#nav li a:hover.item2 {background-position:0px -215px;}
...

example1after.png

We were able to reduce the number of HTTP-Requests by 9 and the total file size of the image(s) by 6.5 KB. That’s a pretty huge improvement for such a little example. Imagine what you could do on a full website.

Popularity: 2% [?]

Post to Twitter Post to Plurk Post to Yahoo Buzz Post to MySpace Post to Ping.fm Post to StumbleUpon

Related posts:

  1. CSS Sprites: What They Are, Why They’re Cool, and How To Use Them (Part 1)
  2. CSS Sprites: What They Are, Why They’re Cool, and How To Use Them (Part 3 – End)
  3. Design Jaket Himpunan

About the Author

Marion Renaldo Rotinsulu, born in Pasuruan on March 9, 1987. Raised in a city that was far away in Sulawesi, Gorontalo named there. In August 2009 has completed the study as a bachelor student (S1) majoring in Electrical Engineering, University of Al-Azhar Indonesia and is the best graduates in these majors. Currently works as a programmer at one multinational company called Streetdirectory, Pte Ltd since August 18, 2009.