CSS: Data URI Scheme, Base64 Encoding

By Xah Lee. Date: . Last updated: .

If you have lots tiny images in CSS, it'll make your site slow, because each HTTP request introduces latency.

CSS Google Plus Twitter Facebook icon link-2
Link with favicons, Twitter, Facebook, Google Plus

One way to solve this problem is to use what's called “Data URI Scheme”. Basically, you encode your image and embed it in your CSS file.

For example, suppose this is your CSS:

a[href*="twitter.com/"] {
background:url(https://twitter.com/favicon.ico) no-repeat left center;

this will match links to Twitter and add a icon in front of the link. [see CSS 3 Selector Syntax]

You can encode it like this:

a[href*="twitter.com/"] {
no-repeat left center;

Inside the background:url(…) is the data URI.

The first part data:image/png;base64, is the MIME type followed by a comma.

The rest string is base64 encoded data of the image.

How to Convert Image to Base64 Encoding

First, if the image is “ico” format, best to convert to png. You can use ImageMagick, like this:

# convert to png using imagemagic
convert favicon.ico favicon.png

[see ImageMagick Tutorial]

Then, you should optimize the png file, make the file size smaller. You can use the program “optipng”.

# optimize the png, makes the file size smaller
optipng favicon.png

Now, you have a optimized png file.

Let's suppose the image we want to base64 encode is named “my_img.png”.

Linux Shell

On Linux, you can use the command base64, like this:

base64 my_img.png | tr --delete '\n' > output.txt


echo base64_encode(file_get_contents("my_img.png"));


print open("my_img.png", "rb").read().encode("base64").replace("\n", "")

Python 3

import base64
print(base64.b64encode( open("my_img.png","rb").read() ).decode("ascii"))

Ruby 1.9

require "base64"
print Base64.strict_encode64(File.open("my_img.png", "rb").read)


use MIME::Base64 qw(encode_base64);
open FH, '<', 'my_img.png';
read(FH, $contents, 10000000);
print encode_base64($contents, "");

JavaScript (node.js)

let fs = require('fs');
console.log( fs.readFileSync('my_img.png').toString('base64') );


〈Data URI Scheme〉 At http://tools.ietf.org/html/rfc2397

Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth