Skip to content

Instantly share code, notes, and snippets.

@Munter
Last active December 14, 2015 19:39
Show Gist options
  • Save Munter/5138615 to your computer and use it in GitHub Desktop.
Save Munter/5138615 to your computer and use it in GitHub Desktop.
Suggestion for new section on browserdiet.com on data-URI background images
Error in user YAML: (<unknown>): mapping keys are not allowed in this context at line 1 column 8
---
order: ?
title: Inline CSS backgrounds
---

This technique is an alternative to using CSS sprites.

A Data-URI is a way to inline the content of the URI you would normally point to. In this example we are using it to inline the content of the CSS background images in order to reduce the number of HTTP requests required to load a page.

Before:

.icon-foo {
  background-image: url('foo.png');
}

After:

.icon-foo {
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII%3D');
}

All browsers from IE8 and above support this inlining technique. IE8 has a maximum data-URI limitation of 32kb.

Both this method and the CSS spriting method require build time tools to be maintainable. This method has the advantage of not requiring manual spriting placement as it keeps your images in individual files during development.

This method has the disadvantage of growing the size of your CSS considerably if you have large images. This might delay the styling of the page slightly. It is not recommended to use this method if you aren't gzipping your CSS during HTTP requests as the size overhead might negate the speed gains you get from minimizing the number of HTTP requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment