Share Using CSS for Icons
Friday, July 17th, 2009During an exploration of CloudFront it was noted that requests were the lionshare of the costs for one application. How much savings could be realized by merging all icon files into one and serving them using positioning in CSS? Quite a bit actually.
First, I created an icon file that is 128 pixels square to hold my 16 pixel square icons. Each of the icons individually averages out to ~700 bytes. After adding all the images, the total filesize for this new icon file was ~21.5K. This already equates to a significant space savings on any page that loads all 64 icons which would translate to ~44.8K. More space could be saved had I used a gif, but I wanted retain the alpha – personal preference. Next I created the necessary CSS to position these images using intelligent names like s-icon-heart to replace images/heart.png, this makes the code very readable. The CSS positioning code for my icon file to support all 64 icons is ~3.6K which needs to be added to the stylesheet sitewide.
Adding the icon file and the CSS together yields a total savings of ~19.7K for pages that use all icons in the file. While not every page uses every icon, stylesheets and images are usually cached by the browser so future requests for these assets won’t incur a trip to the server. Furthermore we’ve eliminated up to 63 http requests which, although individually are quick, cumulatively they add up to serious time for the browser!
You can see how I made my icon file by dropping the icons into a grid in Photoshop. I then save this out as a large PNG. Be aware that older versions of IE do not support PNG transparency so you might get some odd behaviors there. As always test in the browsers you wish to support.
![]()
I then add the necessary positioning elements into my CSS file for each of the icons. Getting the names and positions was probably the most tedious part of the process.
div.icon { width:16px; height:16px; } .icon { background-image: url('images/icons.png'); } .icon-star-bronze-red { background-position: 0 0; } .icon-star-bronze-green { background-position: -16px 0; } .icon-star-bronze-blue { background-position: -32px 0; } .icon-star-gold-red { background-position: -48px 0; } .icon-star-gold-green { background-position: -64px 0; } .icon-star-gold-blue { background-position: -80px 0; } /* ... 58 more definitions */ |
There are a number of ways to then use this in your code. You can point towards a clear.gif, if you’re already using one for positioning or layout. You can apply it as the background image on an element. Get creative.
<!-- using an image --> <img src="images/clear.gif" width="16" height="16" class="icon icon-star-gold-red" /> <!-- using a div --> <div class="icon icon-star-gold-red"></div> |
If you are looking for a kick ass icon library, look no further than the FAMFAMFAM Silk Icons which are available for free under a creative commons license.