Back in the day, I produced video games for a living, so when I heard that sprites were a great way to improve site performance, I had to put my way-back hat on.
A sprite, if you don’t know, is a single graphic file that contains many elements used to display, say, tiles in your favorite side-scroller (Metal Slug, anyone?), or, in this day and age, background elements on a web site. Instead of displaying the entire file, only a portion of the graphic file is revealed. Fortunately, this is a simple thing to do with CSS’s background property.
Excellent candidates for CSS Sprite optimization are gradient backgrounds, rollover-buttons, tab elements, or rounded graphic box elements. Creating a sprite is easy, but tedious. You’ll want to do this only once the design is locked, since going back and making changes can be a pain.
For the purposes of this article, let’s look at a recent example of how CSS sprites reduced page load times dramatically. TheFreelanceNation.com is a client site I did recently where the design was handed to me. The site consists of many rounded “gel” elements, each of which required 9 graphic elements.
By grouping all of the page elements into two files–one for the rounded corners, and another for horizontally repeating elements–the number of overall http requests dropped by almost 70% (120+ down to 35 or so). I was able to reduce this further by grouping and compacting JS files and CSS files, but that’s a topic for another day.
In Photoshop, open the elements you want to group together. Then add each to a master file, making sure to draw guides on the boundaries so you can easily measure the pixel locations later. The rule of thumb is to group elements that repeat together. Meaning if you have elements that repeat-x, you’ll group them in a tall file. Elements that repeat-y will go together in a wide file. Save this in an optimal file format (I find that 8-bit, PNG, difussion dithered is best for all but the most colorful sprite files, in which case 24-bit will do). Experiment in Photoshop’s Save for the Web dialog to get the best result.
Once you have your grouped file ready, adapt your CSS files as follows:
background:url('/images/sprites.png') repeat-x 0 0;
background:url('/images/sprites.png') repeat-x 0 -20px;
background:url('/images/sprites.png') repeat-x 0 -40px;
Notice two things:
1) is the use of shorthand. The background shorthand syntax is “background:[url] [repeat] [xpos] [ypos]. While this isn’t strictly necessary, it makes things a lot cleaner.
2) the starting point of CSS element within the sprite is measured in negative pixels. (It took me a while to figure this one out.)
Play around with this. The technique is surprisingly simple once you get the hang of it, and the results can be stunning. You’ll find initial page loads to be faster, and subsequent cached reloads to be much snappier.