Last Updated: 13 Apr 2011

   |   

Author: dordal

Using One Image for Multiple Buttons (Sprites)

Each time you put an image in your HTML, your browser makes a request to the web server, which then serves that image file to the browser so it can be displayed. Those requests are expensive, so some people have started putting multiple small images (such as images for buttons or icons) into one larger image file, and then using background positioning to display only the appropriate part. That way, the browser only has to make one request to the web server; each 'image' displayed on a page is actually part of a larger image file.

You can see this on big sites like Yahoo. If you go to the Yahoo Homepage and use FireBug to inspect the icons on the left side, you'll see that every single one is stored in this file: http://l.yimg.com/a/i/ww/sp/trough_2.0.gif They use the positioning technique to display only the portion of the file they want (containing a single icon).

Here's how to do it:

  • Make your buttons and put them all in one image. For our example case, we have Save & Cancel buttons (note the black border is unnecessary; it's just so you can see the images better):

  • Make an HTML file which has an element you can attach an image to. In this example, we'll use two <div> elements, but you can use pretty much any block-level element (<div>, <a>, <p>, etc.)
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="button-save"></div>
<div id="button-cancel"></div>
</body>
</html>
  • Finally, make your style sheet and set the width, height & background properties:
#button-save {
	width: 47px;		/* exact button width */
	height: 23px;		/* exact button height */
	/* button background: don't repeat the background, let it scroll with 
	   the page, and find the proper offset for the button in the file */
	background: url('buttons.gif') no-repeat scroll -6px -5px;
}
 
#button-cancel {
	width: 60px;
	height: 23px;
	background: url('buttons.gif') no-repeat scroll -6px -32px;
}

Discussion

Enter your comment. Wiki syntax is allowed: