CSS background image data: base64?

1 min read 205 words

What the heck is all that Gobbledygook in the CSS?

So you have noticed that bit of css that says something like this in the CSS source-code and you have no idea what it could be?
url(“data:image/gif;base64,R0lGODlfMAMEAIABAKysrObm5iH5BAEAAAEALAAAAAAwAwQAAAJOhI+py30Bo5y02ouz3rz7D4biSJbmiabqyrbuC8fyTKPOjedHzff+DwwKh8Si8YhMKku6pvOxjEqn1Kr1is1qt7ynV8cNi8fksvmMTiMLAD4=”) no-repeat scroll 50% 0 transparent

It is a technique called Data URLs and using PHP – or your favourite server-side script – you can generate these nifty little things.

An example of how to generate it in PHP:

<br> .myClassName {<br> background: url(data:image/gif;base64,<?php echo base64_encode(file_get_contents("../images/folder16.gif")) ?>) top left no-repeat;<br> }<br>

What you need to know over and above:
You will need to have your CSS file(s) saved as in the PHP extension ( e.g. myCSSFile.php ).
This allows the server to process the PHP code contained in the CSS, so in a way you have a dynamic CSS file creator.

What’s so good about Data URLs?
They aren’t all that weird after all, they actually help conserve bandwidth due to less HTTP requests. This brings us to the next step you need to know!

Caching problems!
The problem with this approach is that you will need to recalculate the string everytime you change the image, otherwise browsers tend to cache what they remember seeing and use that instead!

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts