Always Twisted

{ Slightly Bizarre Ramblings Of A Front-End Developer }

Sass and Base64 images

Recently I was working on a client site with various triangular carat icons denoting if something was open or closed or whether it was a link. As the images were so small and after optimising them even small i thought I’d encode them in the CSS.

This got me thinking about how to use them with Sass.

Although I use Sass I still like a ‘tidy’ stylesheet before compiling. Adding Base64 encoded images gives me a chunk of text I don’t like the look of in my code. So it got me thinking.


I had a cunning plan. Using a partial (_base64.scss) I thought I could add all my base64 images in there then, using a %placeholder for each one, I could @extend them in to my other stylesheet(s) where needed.

This worked perfectly. In my _base64.scss file I’ve got something similar to this -

%carat-triangle--up {

To which I then included it into something like this -

.error-message {
  // code for error message
  &:before { 
  @extend %carat-triangle--up
  // code for included this icon

Using %placeholder and @extend means I can call the the icon what it is, clearly and concisely. Where as in the compiled CSS file it might be part of the .error-message I would easily be able to tell from the @extend that what it looks like, a %carat-triangle--up.

Now I’ve got some nice icons in the stylesheet saving on HTTP requests but I don’t see them as they’re (to me) hidden away when working on my Sass files.


If you’re using Compass, you can forgo having to create the Base64 images by letting the framework do the work for you. Including the image you want to be a data-uri like this -

background-image:  inline-image(‘carat-open.png’);

When compiled will create the Base64 code for you. So you might not even need a separate partial.


The guys at Mixture are awesome. I mentioned this feature to them a while ago and within 48 hours it was in the app. So if you use Sass, LESS or Stylus you can do the same thing using this code -

background-image: inline-image('carat-open.png');

Will also output the Base64 code when Mixture compiles.

Base64 encoded files

If you’re supporting modern browsers (IE8+) then you’d be easily able to include Base64 images into your compiled CSS file. Note that Base64 encoding adds about 25-30% to the file size of the original image file size so don’t use it for everything. Personally, I never encode anything that’s larger than 4kb as an image.


They’re have been several recent posts about the performance of using Base64 encoded files over using actual images. There is no silver bullet. The best thing to do is test both early and see which will be the best way to go.

This helps me, a tidy set of Sass partials is a tidy mind, hiding the ‘random’ collection of letters and numbers or even the files I’m importing just helps me build my projects out.


HTML Sass Performance Did you like this post? Hire me.
blog comments powered by Disqus