It's mid-2004, and even with the rise of broadband, latency is still our biggest enemy. Most browsers are still limited to only 2 concurrent connections per domain. If your navigation menu has 10 icons and your sidebar has another 10, that's 20 separate HTTP requests just for small graphics. The overhead of the HTTP headers and the TCP handshake is ten times larger than the images themselves.
The solution? CSS Sprites. Instead of 20 images, we create one large image-a 'master sheet'-and use CSS background-position to show only the piece we need.
The Master Sprite Sheet
First, combine all your icons into a single icons.png file using a tool like Photoshop or GIMP. For this example, let's assume each icon is 16x16 pixels and they are stacked vertically.
- Icon 1 (Home): 0px, 0px
- Icon 2 (Email): 0px, 16px
- Icon 3 (Search): 0px, 32px
The CSS Implementation
The magic is in the background property. We define a single class for the base image and then specific classes to "window" into the correct icon.
/* Base style for all icons */
.icon {
display: inline-block;
width: 16px;
height: 16px;
background-image: url('images/master_icons.png');
background-repeat: no-repeat;
vertical-align: middle;
}
/* Specific icon positions */
.icon-home { background-position: 0 0; }
.icon-email { background-position: 0 -16px; }
.icon-search { background-position: 0 -32px; }
Note the negative values for background-position. We are essentially pulling the background image up by 16px to show the second icon.
The HTML Usage
Now, instead of <img> tags, we use a <span> or <i> with the corresponding classes.
<ul>
<li><span class="icon icon-home"></span> Home</li>
<li><span class="icon icon-email"></span> Contact Us</li>
<li><span class="icon icon-search"></span> Find a Product</li>
</ul>
Why This is Better in 2004
- Reduced Latency: One request vs. twenty. This is the difference between a page that feels 'instant' and one that 'pops' into place piece by piece.
- No Flicker on Hover: In 2004, we often use
:hovereffects to change an icon's color. If you use two separate files, the browser won't download the hover image until the user actually hovers, causing a brief blank flicker. With a sprite, the entire sheet is already in memory. - Better Compression: A single large PNG with a shared color palette often results in a smaller total file size than twenty individual small PNGs.
The biggest challenge is maintainability. Adding a new icon means recalculating your vertical offsets and re-saving the master sheet. But for any site serious about performance in 2004, the tradeoff is absolutely worth it. Professional portals like Amazon and Yahoo! are already adopting this for their navigation systems.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development