In a recent project, I decided to use data-URIs for small images to save a few HTTP requests. I’d like to use the same base64 encoded image multiple times in my CSS. But as a performance-concerned developer, I know it will drastically increase my stylesheet’s weight. And I don’t like that idea.

So what to do about duplicate data-URIs in CSS?

    1. Forget about it. Let GZIP do the work for you. Read this great article
    2. Group all selectors and use the data-URI only once. This is as easy as pie if you’re using LESS.
    3. Use a single class just for the background and adjust your markup accordingly. We don’t really want to be doing this, as this requires to add this additional class where you want to use the data-URI.

As the first solution is brilliantly covered by Martin Sutherland on his blog, I’m not going to explore it. Instead, I will detail the second solution.

So let’s we want to apply the same background image 3 times. So we write:

/* This LESS code */n.header {background: data-uri('image/png;base64', 'images/background.png');}n.sidebar {background: data-uri('image/png;base64', 'images/background.png');}n.footer {background: data-uri('image/png;base64', 'images/background.png');}nn/* Will compile into this CSS */n.header,n.sidebar,n.footer {background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAyCAYAAACZDmG3AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccl.../+pXgEGAH6HlYzJaNxNAAAAAElFTkSuQmCC) };

What are the advantages of using LESS you ask me? It’s more flexible and easier to maintain. You don’t have group all 3 selectors manually (LESS will do it for you), which helps you organize you stylesheet the way you want. And, you don’t have manually generate the data-URI using tools like duri.me.

Useful links about using data-URIs with LESS

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *