CSS: Data URI Scheme

By Xah Lee. Date: . Last updated: .

What is Data URI Scheme

Data URI Scheme lets you encode a image file's content directly in CSS (using base64 encoding), without linking a URL.

Data URI Scheme is useful because everytime you link to a image in CSS (such as for background image), browser needs to make a HTTP request, thus slowing down. (but if your web server is using HTTP2, it's not a problem.)

Data URI Scheme Example

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

this will match links to twitter.com and add a icon in front of the link.

〔see CSS: Selector: Match Attribute

You can encode it like this:

a[href*="twitter.com/"] {
background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAACXBIWXMAAABIAAAASABGyWs+AAAApVBMVEX////////////////u9/r////////////////////O5/Dv+f3P6vTP7fi+5PPe9PzO7fmez+HP7/ue0OOOx92v5Pie2/N+v9ie3PSe3/hvvNlgsM9+0/R+1fZPqcxfy/RAoMVQxfNArNY/tuMvmsMvuO0wvPEfkr4QiLYQi7oPrOgPsO4Aib0AkckAlMwAltAAmdQAnNgAn9sAod8ApOMAqeoArO7zdD6kAAAALHRSTlMAAwcMDw8UGB8oMD9CVldXWmBgYnB4foGBiZSfn6Gxtr/CxcrQ29vg7u7z8yG5/9UAAAABYktHRACIBR1IAAAAfklEQVQYGY3B6QKBQBgF0JsZKtmyk+zGkpDlvv+j+Wbif+cAFWhYejiJoTXEMobY3+75+jiA2OWJRvNN8nVpQYxZnJM5rZGC2JKf4kGrAaud8cfAUYuMpSlKnQMd46NU720oTARHJ6frk+Qq8uB4YT9N01k39PCngiDwa6jqCz6DEH0t5c9eAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDEzLTA3LTIwVDA0OjA2OjAxLTA3OjAw/V0jwgAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxMy0wNy0yMFQwNDowNjowMS0wNzowMIwAm34AAAAASUVORK5CYII=)
no-repeat left center;
padding-left:19px
}

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

  1. Optional: convert the image to png first.
  2. Optional: optimize the png file.
  3. Use a base64 program to get the base64 encoding text for the png.

Convert Ico to Png

You can use ImageMagick to convert ico to png.

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

〔see ImageMagick Tutorial

Optimize Png

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

Image to Base64 Encoding

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

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

CSS, Background Image

CSS, Advanced