Inline SVG Data URIs
You'll learn how to embed SVG icons directly in CSS using data URIs to eliminate HTTP requests for small graphics.
What Are SVG Data URIs?
Instead of linking to external SVG files, you can encode the entire SVG markup as a data URI and embed it directly in your CSS. Think of it like carrying a photo in your wallet instead of keeping it in an album at home—you have immediate access without needing to fetch it separately.
A data URI for SVG looks like this:
.icon {
background-image: url('data:image/svg+xml,<svg>...</svg>');
}
When and Why to Use Them
For small icons (typically under 2KB), inline data URIs eliminate HTTP requests entirely. The browser doesn't need to fetch, parse, and wait for a separate file—the icon is already in your CSS. This is perfect for frequently-used UI elements like arrows, checkmarks, or small decorative graphics.
The Encoding Approach
You have two options:
URL-encoded (recommended for SVG):
.checkmark {
background: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"%3E%3Cpath d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/%3E%3C/svg%3E');
}
Base64-encoded (larger but simpler):
.icon {
background: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...');
}
Size Implications
Data URIs increase your CSS file size and cannot be cached separately. A 1KB SVG file becomes roughly 1.3KB as base64 or stays ~1KB URL-encoded. Use this technique only for small, critical icons—not large illustrations. For bigger graphics, keep them as external, cacheable files.
Key Takeaway: Inline SVG data URIs in CSS eliminate HTTP requests for small icons, boosting initial load performance, but increase CSS size and prevent individual caching—use wisely for truly small, critical assets.