Using Data URIs for CSS Background Images
Embed small images and patterns as CSS background-image data URIs to eliminate HTTP requests. Learn syntax, size limits, and best practices for CSS inlining.
Detailed Explanation
CSS Background Images with Data URIs
One of the most common uses for data URIs is embedding small images directly into CSS background-image declarations. This technique eliminates HTTP requests for background textures, icons, and UI patterns that would otherwise require additional round trips.
Basic CSS Syntax
.icon-search {
background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxu...');
background-size: 16px 16px;
background-repeat: no-repeat;
}
Or using percent-encoded SVG (often smaller):
.icon-arrow {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M5 12h14M12 5l7 7-7 7'/%3E%3C/svg%3E");
}
Why CSS Data URIs Are Effective
When a browser parses CSS, it discovers external url() references and must fetch them before rendering can complete. Each fetch adds latency, especially on mobile networks. By inlining small images:
- Eliminates render-blocking requests — The image data is available immediately with the CSS
- Reduces total connection count — Fewer TCP connections needed
- Avoids CORS issues — No cross-origin concerns since data is inline
- Works offline — No network needed for the embedded assets
Practical Patterns
Repeating background texture:
body {
background-image: url('data:image/png;base64,...');
background-repeat: repeat;
}
CSS sprite replacement:
.btn-primary::before {
content: '';
display: inline-block;
width: 16px;
height: 16px;
background-image: url('data:image/svg+xml,...');
}
Size and Caching Trade-offs
When you embed data URIs in CSS files, the CSS file itself grows. If the CSS is cached, the embedded images are cached with it. However, if you change one image, the entire CSS file cache is invalidated. For frequently changing images, use external files instead.
Use Case
You are creating a CSS-only icon system for a design component library and want every icon to be self-contained within the stylesheet, requiring no separate image files to ship.