Data URIs for SVG Images
Embed SVG images as data URIs using Base64 or percent-encoding. Learn which encoding produces smaller results and how to optimize SVG data URIs.
Detailed Explanation
SVG Data URIs: Base64 vs Percent-Encoding
SVG is unique among image formats because it is text-based XML, which means you have two encoding options for data URIs: Base64 and percent-encoding. Choosing the right one can significantly reduce the data URI size.
Base64-Encoded SVG
background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0...');
Percent-Encoded SVG (Usually Smaller)
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='%23fff' stroke-width='2'%3E%3Cpath d='M5 12h14'/%3E%3C/svg%3E");
Size Comparison
For a typical 500-byte SVG icon:
- Base64: ~668 bytes (33% overhead)
- Percent-encoded: ~550-600 bytes (10-20% overhead)
The difference grows with larger SVGs. Percent-encoding wins because most SVG content is printable ASCII that passes through without encoding. Only a few characters need escaping:
| Character | Percent-Encoded |
|---|---|
< |
%3C |
> |
%3E |
# |
%23 |
" |
%22 (use single quotes in SVG) |
Optimizing SVG Before Encoding
- Remove unnecessary attributes:
xmlnsis only needed at the root - Use short attribute values:
fill='none'instead offill='transparent' - Remove comments and metadata: Strip editor-generated cruft
- Simplify paths: Use SVGO to optimize path data
- Use currentColor:
fill='currentColor'lets CSS control the color
Browser Compatibility
All modern browsers support both Base64 and percent-encoded SVG data URIs. Internet Explorer 9+ supports SVG data URIs, but IE 8 does not support SVG at all.
Use Case
You are building a Tailwind CSS plugin that provides utility classes for common SVG icons, and you need each icon to be self-contained in the CSS without external file dependencies.