CSS Sprites

Contact Us or call 1-877-932-8228
CSS Sprites

CSS Sprites

A CSS sprite is an image file that contains several graphics used on a web page. By showing different parts of the sprite in different locations, it appears that there are several different images, but they are all contained in a single file, which translates to a single download.

As a simple example, let's look at the images we used for tabbed navigation earlier. Here they are again (magnified): Tabbed Navigation Image

Instead of having three different images, let's combine these into a single image (magnified below): Combined Single Image

Now let's see how we can play with the background positioning to make use of this single tabSprite.gif image rather than the three separate images.

Code Sample:

---- C O D E   O M I T T E D ----
	#mainMenu a {
		background:transparent url(Images/tabSprite.gif) 0px 0px repeat-x;
	#mainMenu a:hover {
		background-position:0px -37px;
	#mainMenu a:active {
		background-position:0px -74px;
---- C O D E   O M I T T E D ----

Code Explanation

Things to notice:

  • In the rule for #mainMenu a, we have changed the background image to Images/tabSprite.gif and added positioning of 0px 0px. That's because we want the link state to show the top portion of our tabSprite image.
  • In the rule for #mainMenu a:hover, we have replaced the rule for background with background-position:0px -37px;. That's because we inherit the background image from the #mainMenu a, but we want to bump it up 37 pixels so that it shows the middle portion of the image.
  • We do the same thing with the rule for #mainMenu a:active, but this time we bump it up 74 pixels.

The more graphic heavy a page is, the more it can benefit from using CSS sprites. Consider this small example we have just shown. The table below shows the file sizes for the three original graphics and then for the sprite:

Comparing CSS Sprite File Size with Separate Images
File Size
link.gif 590 bytes
hover.gif 612 bytes
active.gif 378 bytes
Total: 1,580 bytes
tabSprite.gif 817 bytes
Difference: 763 bytes

That savings of 763 bytes translates to a savings in file size of 48%. Add to that the overhead associated with each http download for the separate images and you'll find the savings can be significant.

Open CssBackgroundTricks/Demos/sprite.html for a more complex example that uses a single image to create a library of thumbnails that highlight when the user hovers over them. Check out the code and you'll see that only a single graphic is used.