A Short Primer on the Optimization and Design Benefits of Using CSS Sprites

I love golf.

There aren’t many better feelings in the world than that of stepping up to an elevated tee looking over spectacular scenery and unleashing a perfectly arching shot that lands softly on the green just a few feet away from the pin.

I don’t get to experience that feeling very often, but I love golf nonetheless.

This week our local course, which has hosted a PGA event before, dropped their price of eighteen holes and a cart from $70 to just $10. I made several tee times.

So yesterday I was out hacking around with several buddies losing more balls than I care to admit when one of them asked me why it was so cheap?

I had talked to the guys in the pro shop and they told me they were not going to do any formal advertising this year and this was their way of getting the word out about the course. They wanted to get as many people as possible to play and then spread the word about how nice the course was.

My friend who is a small business owner thought this was a brilliant marketing strategy and asked:

Why have I never done something like this before?

It’s a question many people have asked throughout history as they stumble across a strategy or technology that has always been available to them, but for whatever reason they didn’t hear about it — or they did hear about it and chose to not follow up and learn more.

This has been my relationship to CSS sprites.

Even though CSS sprites have been around in concept since about 2003 — and have been in mainstream use since 2004 — I never got around to using them because I didn’t think they offered enough. I can now admit that I was wrong, and have found numerous benefits to using them in traditional web design and development.

A Primer on CSS Sprites

In case you’re like me and arrived late to the sprite train let me go over the basics with you.

A sprite is one image that is made up of lots of images. Look at the example below. On the Copyblogger site we use 35 different images that are not intended to be changed often. We could produce each of the images separately but for the reasons I’ll list below we’ve chosen to combine all 35 into one image.

So on the left side you’ll see the single image sprite and the right side is all 35 individual images.

CSS Sprites Sliced

The way we reference all the images is by calculating their position in the image and then using those numbers in the background-position property in our css.

For example notice the social icons for Facebook, Twitter and our RSS feed. Each of these have rollovers. In our style sheet we will define the initial position of the Facebook icon.

#social-icons .facebook {
    background: url(images/sprites.png) -292px -301px no-repeat;
}

Why are we using negative numbers?

When calculating the position of an image, the top left corner is always 0. Anything to the right and down is a negative number. In the image below you can see that the Facebook icon starts at 292 pixels on our horizontal axis or the “x” axis. And the image begins 301 pixels down on our vertical or “y” axis.

CSS Sprites Zoomed

For our rollover we need to define the hover properties for our background-position element.

#social-icons .facebook:hover {
    background-position-y: -317px;
}

Notice that we only had to change the value for the vertical axis because the horizontal number never changes.

One more thing that is very important …

You need to define the width and height of the image or else your container will show as much of the sprite as its size allows. So our final css declaration ended up looking something like this:

#social-icons .facebook {
    background: url(images/sprites.png) -292px -301px no-repeat;
    display: block;
    height: 16px;
    width: 16px;
}

#social-icons .facebook:hover {
    background-position-y: -317px;
}

Advantages of Using CSS Sprites

Reduces the number of http requests
The main reason to use CSS sprites is to cut back on http requests. Every time a new visitor hits your site their browser will request each image from your server. If your home page loads up 35 different images that is 35 separate times the browser has to go back to the server and ask for one more thing.

This is kind of like forcing your mailman to deliver one piece of mail to your mailbox at a time and then making him go back to the postoffice to get the next one. After the 30th trip he’ll probably want to spray you down with his dog mace.

Improves SEO
This might seem strange to you but considering that google and other search engines are now ranking sites based on speed, every http request and kb matter. The faster your site performs, the higher search ranking you’ll receive.

Reduces overall image size
In most cases, combining all of your reusable assets into one file will be smaller than if you sliced them individually. As I stated above, on the Copyblogger site we use an image sprite that has 35 separate images. Combined together the file size is approximately 74kb. Sliced and individually saved, the file size jumps to over 100k.

Now those of you with fancy high speed connections may be scoffing at a paltry 30k but those people with mobile phones on slow connections are thanking us. As Kevin Durrant and Doodle Jump have taught us — every kb matters.

Hopefully you’re not like me and have been shunning the wonderful world of sprites all these years. If so, take heed to the immortal words of En Vouge and free your mind because the rest will surely follow.

Comments

  1. Hi Josh
    Did some reading about sprites years ago – mainly used for navigation images, active, current… that sort of thing.

    Nevere realised that the idea could be used for 35 images!

    As you say, Google now has page load speed in the algirithm so every kb counts.

    Good read and informative as ever.

    • Yeah, its kind of crazy how “old” techniques still yield new fruits.

      Thanks for the kind words.

  2. I really need to work on this! I can see the benefits, but it seems like a pain to setup and figure out.

    • Its really not – especially if you don’t have that many images. If you’re working in Photoshop or Illustrator its really just a drag and drop from your individual files into the new file. The time consuming part would be figuring out the positioning.

      Some people line all their sprite images to the left edge so they only have to calculate the y axis.

      And just think, if you wanted to update rollovers for those social icons you would only have to open 1 file instead of 6!

      As with anything it gets easier the more you do it.

  3. Hi and thanks for the post.

    One question: what kind of images can be put into a sprite? Does it make sense to put the background, header or advertisement banners into it? Or just the theme’s images? For example, the ones in wp-content/themes/mytheme/images/…

    Thanks in advance.

    • I would suggest using images that will not be updated very often. These would include background images, icons, and other decorative assets.

      • Even if the background is a 800×800 custom pattern and 80Kb size?

        • It depends. Since a number of your assets depend on your sprite loading with a large file size the user will not see the other images as quickly.

          I probably would keep that bg image separate.

  4. I’m glad I read this. I’ve been playing around online for years and for some reason, I’ve chosen to ignore sprites. I can’t even explain why.

    So, if I’m understanding this correctly, say I download a pattern from subtlepatterns.com, I can toss it in the sprite, define its top left corner, give the width and height dimensions, and allow it to repeat on both the x and y for, perhaps, my site background?

    • Dude, right there with you.

      Yes you can – we do that on a number of our sites (with subtle patterns too!)

  5. Great storytelling. Love reading articles that are written creatively. I agree that using CSS Sprites have advantages however to better inform the users, it is crucial that you point out the disadvantages as well.

    Time Consumption:

    Maintaining sprites is a pain. I highly recommend using CSS sprites once you have finalized every single detail. If you decide to make any size adjustments, specially to images that are in the middle, you can easily find yourself modifying a lot of CSS classes adjusting the background position.

    Perfection is Crucial:

    You have to be very smart about the spacing between each item. If you are not careful on your first attempt, you are in for a whole lot of trouble. If a page is zoomed (a common browser function), you can see sprite fractures where an image that didn’t have enough spacing leaks into the design. Getting this spacing right specially for someone starting out will require a lot of trial and error. Not saying that you won’t get good at it later on. But be prepare to do a lot of CSS modifications because it is a fact that users do ZOOM their pages. Sometimes even unknowingly. True story: My mom while browsing a site on the laptop accidentally moved her fingers on the touchpad which caused the screen to zoom in. She liked the view and kept it as is. She thought it was some sort of upgrade on the OS. But there are a lot of users like this.

    Since you are creating your website and content for USERS (a lot of which the Penguin update was focused on), you need to make sure that your site works for your users.

    Also not sure if this issue is fixed on browsers yet, but I remembered reading about it. There are times when designers have really really long images… like thousands of pixels in height for whitespace. While that image will compress well, so you will say (oh one image 26k) it is all good. But the thing is that browsers don’t render compressed image data. So after it downloads it, it has to decompress it. So a 26k image will use almost 75MB in memory. Here is the article for reference:

    http://blog.vlad1.com/2009/06/22/to-sprite-or-not-to-sprite/

    If you are creating your site for users, chances are that your images will be stored in the browser cache anyways. So whether you have 1 big sprite image, or 30 small images, it wouldn’t matter much on the next page load.

    I usually put small icons and such in a sprite (social icons), but not the other elements until I’m 100% sure that the site is totally done and will not require changes.

    I think a good sprite workflow is shared by Chris Coyier here that I think that others will find useful:

    http://css-tricks.com/css-sprites-workflow/

    • Good points. Thanks for the links.

      I think the time consumption can work the other way too. With all my images in one place I don’t have to manage 35 separate images just one. I think its one of those things that if you spend the time at first you’ll reap more benefits at the end.

  6. Jonathan Wilson :

    Great post, Josh! Thanks for making it simple to understand! I’ve shunned the idea of using sprites, until today! :)

  7. “A sprite is one image that is made up of lots of images.”

    So that is what a sprite is. All this time I thought a sprite was a soft drink made by Coca-Cola. No just kidding.

    But this is very good explanation of a CSS Sprite and easy to understand. I will in the near future change my blog images that will not change often to a sprite then use CSS to align them. I didn’t realize the difference it would make.

  8. Thanks for the article. I’ve used them some, but not to the extent I could be. Thanks for reminding me to retrain myself on them!

  9. Hey Josh

    Thanks for explaining this is an easy way to understand. I finally get it!
    Will put it to work soon.

  10. With all images in one place, every website will be much faster :)
    I am not familiar with coding, but I do love CSS sprite. Maybe I’ll hire some designers to work on my websites.

  11. How does using sprites for social icons compare in load time to using the Genesis Social Icons plugin? Or, is it a case of apples to oranges?

    • The Simple Social Icons plugin actually uses sprites – so its more of a case of comparing apples to apples :)

  12. I got some personal experience in using CSS sprites, but we need to consider some other points also. It is not always necessary to use css sprites as it is a bit difficult to maintain. Thanks for this great article.

  13. Excellent breakdown. I’d been wondering how much sprites might help some of my sites, but image design is just not my strong suit. If it takes the talented ones hours to make sprites, I shudder to think how long it might take me!

    obligatory musical nitpick: the ladies spelled it En Vogue, and they didn’t even have the most popular version of that phrase, neither the original version nor the “clean” version.

    The original, “Free Your Mind and Your *ss Will Follow” was Funkadelic’s circa 1970-71, the title of their album that year. Since so many members of Funkadelic were also shared with Parliament, it would crop up in Parliament and P-Funk performances all through the 70s and 80s.

    I feel so old :)

    • Thanks for the music history :)

      Sprites don’t require a lot of image design expertise – in fact the only thing really required is to able to put the images into one image and figure out the css positioning. If that seems daunting there are a number of automatic generators available to help you. Just google sprite generator and you’ll be spriting in no time!

  14. Thank you for this article. I’ve been trying to learn about sprites for two years now. This article and the comments may finally get me on my way to trying them out!

  15. I was searching about CSS sprites and got here. I love the way I can increase my pagespeed by using Sprites

  16. Thank you! I have image files, with a bunch of icons on one page, and I never knew how to use them and didn’t know what search tern to use to try to find …
    Aha! they’re called sprites! Thank you!

  17. I always wondered what actually “Combining images into sprites” meant. Now I have understood the concept and I’m going to try this out on my blog.

  18. Nice article!

    How ever im not so sure it will save me time, but as you sad that will probarly take a while before it does!

    On w3 schools is a good article about it asswell : http://www.w3schools.com/css/css_image_sprites.asp

    I do use it for hovers, cause there is absolutly no loading time using sprites! So even if the hover isnt in your cache yet it shows up directly wich is nice!

  19. Great Article Josh! Thanks so much. Very clean and clear, really helped me get my head around it!

    (This part’s sarcastic!) Just when I thought I was going to get a good night’s sleep! Now I have something new to stay awake all night doing! Thanks man!

    • I know what you mean – when I get excited about something sleep just goes out the window!

  20. Sounds like a good idea, especially that speed is a material factor in Google’s algorithm. However, this will eat up a lot of time particularly those who are using massive amount of images. Nonetheless, this one’s a great tutorial that’s easy to understand. I have to commend your writing skills – ’twas creative and informational. Thanks.

  21. Thank you for this article. I’ve been trying to learn about sprites for two years now. This article and the comments may finally get me on my way to trying them out!

  22. Josh, I really enjoyed your article and examples of how and why to use CSS Sprites. Thanks for teaching me something new today. – ryan