CSS: Data URI Scheme

By Xah Lee. Date: . Last updated: .

Data URI Scheme lets you encode a image file's content directly in CSS, 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.)

For example, suppose this is your CSS:

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

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/"] {
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

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 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

PHP

<?php
echo base64_encode(file_get_contents("my_img.png"));
?>

Python

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)

Perl

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') );

Reference

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

See also: CSS: Background Image

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

CSS Basics

  1. Basics
  2. Tag Matching Tutorial
  3. Selector Syntax
  4. Units

Color

  1. Color Syntax
  2. Color Names
  3. Opacity
  4. Linear Gradient
  5. Radial Gradient

Font

  1. font-family
  2. Standard Web Fonts
  3. font-size
  4. Meaning of Font Size
  5. Font Weight
  6. Chinese Font Names

Box Model

  1. Border
  2. Outline
  3. Margin vs Padding
  4. Box Sizing

Layout

  1. Layout Tutorial
  2. Display Property
  3. Position: static, relative, fixed, absolute
  4. Pure CSS Table
  5. Tabbed Menu
  6. 3 Columns Page Layout
  7. Multi-Column Layout for Text Flow
  8. Fix Element to Window
  9. Centering
  10. Flowing List
  11. z-index
  12. Text Over Image
  13. Text Flow Around Image
  14. OverFlow, Scrollbar

Transform/Animation

  1. 2D Transform
  2. Transition
  3. Animation

Line Wrap, Justification

  1. Line Wrap
  2. Text Alignment, Justification
  3. Match first-letter and first-line
  4. “:before”, “:after”
  5. Text Decoration: Underline, Overline, Line-Through
  6. Letter Spacing, Word Spacing

Box Decoration

  1. Box Shadow
  2. Text Shadow
  3. Round Corners
  4. Background Image
  5. Image Rollover

Misc

  1. Computed Style
  2. Pseudo Class vs Pseudo Element
  3. Media Query
  4. Variable
  5. calc
  6. Reset
  7. user-select
  8. Data URI Scheme
  9. protocol-relative URL
  10. Default Unit
  11. Declaring Character Set in CSS File
  12. Jargons Explained: Tag, Element, Node, Object, Attribute, Property, Method
  13. Display Table on Small Screen
  14. Fixed Aspect Ratio
  15. Add Icon to Links
  16. Progress Bar Example

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog