elefcode
← All guides

Web & APIs · 4 min read

Data URIs: Embedding Images with Base64

A data URI lets you put a file directly inside HTML or CSS instead of linking to it. It saves a network request, but it is easy to overuse. Here is how it works and when it is worth it.

Try it yourself with the related tool.

Convert an image to Base64 →

Advertisement

The format

A data URI looks like data:image/png;base64,iVBORw0KGgo.... It has the media type, an optional ;base64 marker, a comma, and the data. It can be used anywhere a URL can: an <img src>, a CSS background-image, or a favicon link.

The 33% size penalty

Base64 represents every three bytes as four characters, so an embedded image is about a third larger than the file. Gzip or Brotli recovers some of that, but not all. The data is also re-downloaded with every page that includes it, rather than cached once as a separate file.

When inlining helps

Inline very small images — a tiny icon, a loading placeholder, a blurred preview — where the cost of a separate request outweighs the extra bytes. Inline images in HTML emails, where external images are often blocked by default. And inline assets in a single self-contained HTML file meant to be shared or opened offline.

Use SVG text for SVG

SVG is already text, so you can skip Base64 and URL-encode it instead: data:image/svg+xml,%3Csvg ...%3E. The result is smaller and still readable. For anything larger than a few kilobytes, a normal file with good cache headers is almost always the better choice.

Related guides