The Mystery Of CSS Sprites: Techniques, Tools And Tutorials

Quick Summary

CSS Sprites are not new. In fact, they are a rather well-established technique and have managed to become common practice in Web development. Of course, CSS sprites are not always necessary, but in some situation they can bring significant advantages and improvements – particularly if you want to reduce your server load. And if you haven’t heard of CSS sprites before, now is probably a good time to learn what they are, how they work and what tools can help you create and use the technique in your projects.
The term “sprite” (similar to “spirit,” “goblin,” or “elf”) has its origins in computer graphics, in which it described a graphic object blended with a 2-D or 3-D scene through graphics hardware. Because the complexity of video games has continually increased, there was a need for smart techniques that could deal with detailed graphic objects while keeping game-play flowing. One of the techniques developed saw sprites being plugged into a master grid (see the image below), then later pulled out as needed by code that mapped the position of each individual graphic and selectively painted it on the screen.
You may want to take a look at the following related posts:
* 53 CSS-Techniques You Couldn’t Live Without
* Powerful CSS-Techniques For Effective Coding
* 50 Extremely Useful and Powerful CSS Tools
* CSS Float Theory
* CSS Specificity

Table of Contents

Members support Smashing

Wonderful, friendly people who keep this lil' site alive — and get smarter every day.

CSS Sprites are not new. In fact, they are a rather well-established technique and have managed to become common practice in Web development. Of course, CSS sprites are not always necessary, but in some situation they can bring significant advantages and improvements – particularly if you want to reduce your server load. And if you haven’t heard of CSS sprites before, now is probably a good time to learn what they are, how they work and what tools can help you create and use the technique in your projects.

What Are CSS Sprites?

The term “sprite” (similar to “spirit,” “goblin,” or “elf”) has its origins in computer graphics, in which it described a graphic object blended with a 2-D or 3-D scene through graphics hardware. Because the complexity of video games has continually increased, there was a need for smart techniques that could deal with detailed graphic objects while keeping game-play flowing. One of the techniques developed saw sprites being plugged into a master grid (see the image below), then later pulled out as needed by code that mapped the position of each individual graphic and selectively painted it on the screen.

Sprites were displayed over a static or dynamic background image, and the positioning of the sprite was controlled simply by the hardware controllers. The term was coined because the sprites seemed to “haunt” the display and didn’t really exist in the graphic memory.

The Pokemon Sprite Sheet, consisting of over 1000 graphic objects. Found here. You can click on the image for the larger version (thanks, Ryan!).

Time passed, and at the beginning of the 2000s, when progressive Web designers started to seek alternatives to JavaScript-based rollover menus (with onMouseOver and onMouseOut effects), sprites saw a renaissance in Web development. With CSS, the simple implementation of sprites was possible, and it was much easier and clearer than its JavaScript-based predecessor.

“You must unlearn what you have learned!” Meet the brand new episode of SmashingConf San Francisco with smart front-end tricks and UX techniques. Featuring Yiying Lu, Aarron Draplin, Smashing Yoda, and many others. Tickets now on sale. April 17-18.

In 2004, Dave Shea suggested a simple CSS-based approach to CSS sprites based on the practice established by those legendary video games. In this case, multiple images used throughout a website would be combined into the so-called “master image.” To display a single image from the master image, one would use the background-position property in CSS, defining the exact position of the image to be displayed. Any hover, active or focus effects would be implemented using the simple definition of the background-position property for the displayed element.

When the page is loaded, it would not load single images one by one (nor hover-state images per request), but would rather load the whole master image at once. It may not sound like a significant improvement, but it actually was: the main disadvantage of the onMouse effects is that JavaScript-based hover effects require two HTTP requests for each image, which takes time and creates that unpleasant “flickering” of images. Because the master image is loaded with the whole page only once with CSS sprites, no additional HTTP requests are needed for hover, active or focus effects (because the image is already loaded), and no “flickering” effect occurs.

Consequence: CSS sprites reduce HTTP requests and the loading time of pages. This is the main reason why CSS sprites are often used on websites with heavy traffic, where millions of page impressions would need “only” a tiny fraction of what could otherwise be 30,000,000. Hence, CSS sprites are commonly used, particularly for navigation (such as for hover effects), icons and buttons.

Where Are CSS Sprites Used?

CSS sprites can be used in various settings. Large websites can combine multiple single images in a meaningful manner, creating clearly separated “chunks” of the master images – the purpose being to keep the design maintainable and easy to update. The large empty space between the images is often used to make sure that the text resizing in browser doesn’t cause side effects such the display of multiple images in the background. In fact, sprites usually work well in a pixel-based design, but they are hard to use in elastic (em-based) designs due to the restricted background-position-property. Essentially, the structure that sprites take depends on the trade-off between maintainability and reduced server load; thus, it varies depending on the project you are working on.

Here are some inspiring (and not so inspiring) examples:

Xing
Xing uses various icons and buttons, as well as its logo, in the sprite.

Digg
Digg has quite an esoteric sprite, with small arrows and brackets. The large empty space between the images is used to make sure that text resizing doesn’t display multiple images as the background image. You can explicitely define width and height in pixels, so that this problem does not occur – however, in this case the resized text will never break out of the defined box, thus possibly making the text unreadable. Consequently, you must be cautious when using spriting for buttons with variable text labels. For those buttons, you should define font size in pixels also. Or just use the large empty space in the sprite (thanks, daftie!).

Yahoo
Yahoo has nice icons in its sprite, spread out equidistant from each other.

Google
Google sticks to its minimalist design principle with its minimalist CSS sprite.

Dragon Interactive
A design agency with a colorful, vivid CSS sprite for the navigation menu.

TV1.rtp.ptA huge colorful and qute chaotic CSS sprite on a site of a Portugiese TV-channel (thank you, António Manuel Cardoso!).

CSS Sprites are used to combine many frequently used graphic elements, such as navigation elements, logos, lines, RSS icons, buttons, etc. Conversely, they are not used for any kind content that is likely to change frequently upon release.

How Yahoo.com and AOL.com Improve Web Performance With CSS Sprites
Some of the busiest websites on the Web use CSS sprites to save on HTTP requests. This article shows how Yahoo! and AOL use sprites to improve performance. Note: some devices (the iPhone being the most notable) apply sprites in a memory-intensive way, which slows the device to a crawl.

Sprite Optimization
Dave Shea ponders whether it actually makes sense to create large CSS sprites, combining all elements into a single image and then displaying them with the background-position property in CSS. Answer: No, do not over-complicate things. Instead, find a good compromise between quick loading time and maintainability.

Creating Easy and Useful CSS Sprites
A detailed introduction to CSS Sprites by Ignacio Ricci. All files can be downloaded as well.

Is your pattern library up to date today? Alla Kholmatova has just finished a fully fledged book on Design Systems and how to get them right. With common traps, gotchas and the lessons she learned. Hardcover, eBook. Just sayin'.

Screencasts about CSS Sprites

How to Use CSS Sprites
David Perel explains the basics of CSS sprites and how to use them in your website design. 10 minutes.

How To Use CSS Sprites
This screencast, Smashing Magazine author Chris Coyier shows how to use CSS sprites in practice, by taking what would have been eight different images and combining them into one. As an added bonus, he then expands on the idea with jQuery by building a little accordion widget.

Faster Page Loads With Image Concatenation
For complex web apps, the quantity and resulting latency of icons and images used can greatly affect page load times. And developers usually try to reduce, rather than increase, page load times for their sweet Web apps.

CSS Image Maps With CSS Sprites

With CSS Sprites, the hover effect doesn’t have to be applied to the whole element. Using a negative background-position value, you can create pure CSS-based image maps. Below, you’ll find some techniques in which CSS sprites are used for this purpose.

CSS Image Maps Using Sprites
A basic example of a CSS-based image map with a negative background-position value. Try hovering over the image. Compare this with the classic example without CSS sprites.

CSS Sprites Techniques

CSS Sprites 2
Dave Shea expands on the classic CSS sprites technique with jQuery. His technique allows for animation between link states, while still being fully degradable for visitors who do not have JavaScript enabled.

Background Repeat and CSS Sprites
CSS sprites are a great way to improve the loading speed of your pages. One of the problems you might face with sprites is how to deal with cases where the background repeats. The rule is pretty simple: if you want the background to repeat vertically (top to bottom), place the images in the sprite horizontally (left to right) and make sure the individual images in the sprite have the same height. For the opposite case, when you want to repeat horizontally, sprite vertically.

How to Preload Images When You Can’t Use CSS Sprites
This article addresses the problem that occurs with CSS sprites when the user resizes text. The idea is to combine the images into two images, rather than one. Then you place the image being shown on hover as the background image of another element (preferably a containing element), positioned just off screen.

CSS Sprite Generators

Data URI Sprites
DURIS (Data URI [CSS] Sprites) is a new method to manage website’s background images. It’s aimed to replace classical CSS Sprites. The new technique allows you to apply any corrections to your make-up, allows you to minimize number of requests for design-related data that is used on the webpage and uses text (non graphic) format of image data presentation. It also solves all problems with scaling for background images and combines images of different types and axes of repetition.

Spritr
This simple tool lets you upload multiple images and generates CSS code for the sprite.

Sprite Creator 1.0
This tool allows you to upload an image and create the CSS code for selected areas of the sprite.

CSS Sprites Generator
This tool allows you to upload multiple files and generate a sprite out of them. It also gives you the CSS code (the background-position value) for each image in the sprite.

Projekt Fondue CSS Sprite Generator
This generator lets you ignore duplicate images, resize source images, define horizontal and vertical offset, define background and transparency color, assign CSS class prefixes and various other things. It also supports many languages. The source code is available for downloading and is covered by a BSD license. Want to run a local copy? Well, you can do that, too.

SmartSprites
A Java-based desktop application that parses special directives that you can insert into your original CSS to mark individual images to be turned into sprites. It then builds sprite images from the collected images and automatically inserts the required CSS properties into your style sheet, so that the sprites are used instead of the individual images.

You can work with your CSS and original images as usual and have SmartSprites automatically transform them to the sprite-powered version when necessary. A PHP version is available as well. Open-source. Check also Chris Brainard’s Sprite Creator 1.0.

Bonus: How Does The background-position Property Work?

The background-position property, together with CSS specificity and CSS floats, is probably one of the most confusing and counter-intuitive of CSS properties.

According to CSS specifications, the background-position takes two (optional) arguments: horizontal position and vertical position. For example:

Using this property, you can define the exact position of the background image for the block-level element (list item li). You can use either % or px units (or mix both) to define the starting position (i.e. the upper-left corner) of the displayed part of the master image. Alternatively, you could use the following keywords: top left, top center, top right, center left, center center, center right, bottom left, bottom center, bottom right.

Hence, in background-position: x% y%, the first value is the horizontal position, and the second value is the vertical position. The top-left corner is 0% 0%. The bottom-right corner is 100% 100%. If you specify only one value, the other value will be 50%.

… then the background-image will be positioned 19 pixels from the left and 85 pixels from the top of the list item element.

As SitePoint’s reference article explains: “a background-image with background-position values of 50% 50% will place the point of the image that’s located at 50% of the image’s width and 50% of the image’s height at a corresponding position within the element that contains the image. In the above case, this causes the image to be perfectly centered. This is an important point to grasp – using background-position isn’t the same as placing an element with absolute position using percentages where the top-left corner of the element is placed at the position specified.”