Helpful Tools For Web Developers: – Base64 Encode Your Images

One of the more recent CSS techniques I’ve learned is how to base64 encode images and fonts directly into a CSS file. Why would you do something like that? Here’s a couple of the main benefits of CSS encoding:

  1. Fewer HTTP Requests: Only the CSS file needs to be requested so there’s fewer HTTP requests to the server.
  2. If your design includes custom fonts, you can embed the required font files directly in the CSS. This helps guarantee your design will be viewed as intended.

How to Go About Encoding Images

There’s two main approaches you can take when it comes to base64 encoding your images: Writing a small script using a backend language like PHP or using a preexisting tool. If you’re not the programming type, I recommend It’s a really simple drag-and-drop tool that not only generates the base64 string, but also gives you the CSS you’ll need to use on your website (I’ve truncated the encoded image text for brevity):

    width: 500px;
    height: 628px;
    background-repeat: no-repeat;
    background-image: url(data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD//gAuSGF...)

Things to Keep in Mind

Per the FAQ, there are some disadvantages to using Base64 encoded images in your CSS:

  • The size of the embedded code is 1/3 larger than the binary equivalent, however this can be reduced to 2-3% using gzip compression.
  • Internet Explorer 7 is not supported.
  • Internet Explorer 8 limits data URIs to a maximum lenght of 32KB.
  • Data URIs don’t carry a filename like a normal file,
  • Data URIs need to be re-enconded and re-embedded every time a change is made to the image.

Regardless of whether or not Base64 encoding is the right way to go for your site, I still think that is a great tool that is elegantly designed and dead-simple to use. If you want to learn more about its creators, check out Patrik Larson on Twitter as well as Tiago Duarte.