Optimizing CSS with Base64 Embedded Images (with Bonus Utility!)
As I design a new site (current site | early demo of new site), I am working through what combination of technologies (CDN, sprites, caching, gzipping, etc.) we want to use to optimize it. One tool I’m looking at is embedding images in CSS with base64 strings. Instead of the browser needing to make several calls, one for the CSS file and then one for each image, base64 embedding means that all of the images are embedded within the CSS file itself.
It’s great for small images or images that only show up on :hover or mouseover and you don’t want there to be any delay in the image appearing. Here’s what it looks like:
background: transparent url(myimage.jpg) top left no-repeat;
CSS with Base64 Embedded Image
background: transparent url(data:image/png;base64,LONG-STRING-OF-BASE64-TEXT) top left no-repeat;
Problems with Base64
- Works in all browsers except IE6 and IE7. Solution: use a conditional comments to give IE6/7 a stylesheet that still references the images.
- Base64 is bigger than real images: In my tests a base64 encoded string image is somewhere around 150% the size of a regular image. This means it’s unusable for large images.
- Hard to manage: If you change the image, you’ll need to reembed the base64 string. You also have to maitain a separate IE stylesheet.
How to manage it
To help figure out which images were worth embedded and help
manage it, I developed a small utility that analyzes a CSS file and allows you to select which images you want to embed. You can also preselect them by adding a comment somewhere within your CSS declaration that says
What It Does
- Finds all image URLs in your CSS file (note: no CSS3 multiples or borders)
- Shows the size difference between the image and the base64 string
- Shows the final size output size and the GZipped size for comparison to the original
- Removes comments and whitespace if you want
- Creates a new base64 stylesheet and a IE6/7 stylesheet with references to the original image
- Download CssImageEmbedder.zip (9.55 kb)
- Requires: .NET Framework (sorry! It was just faster than doing it in AIR)