Embedding Base64 in CSS
Embed Base64-encoded images and fonts in CSS using data URIs. Learn the syntax for background images, custom fonts, cursors, and performance trade-offs.
Detailed Explanation
CSS supports data URIs anywhere a url() function is used, allowing you to embed images, fonts, and other assets directly in your stylesheets. This eliminates additional HTTP requests but increases the CSS file size.
Background images:
.icon-search {
background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0i...);
background-size: 16px 16px;
background-repeat: no-repeat;
}
.hero-pattern {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAA...);
background-repeat: repeat;
}
Custom fonts:
@font-face {
font-family: "MyFont";
src: url(data:font/woff2;base64,d09GMgABAAAAAAR...) format("woff2");
font-weight: normal;
font-style: normal;
font-display: swap;
}
Custom cursors:
.custom-cursor {
cursor: url(data:image/png;base64,iVBORw0KGgo...) 16 16, auto;
}
List style images:
ul.custom-bullets {
list-style-image: url(data:image/svg+xml;base64,PHN2Zy...);
}
SVG special case: SVGs in CSS can be embedded without Base64, using URL encoding instead:
.icon {
background-image: url("data:image/svg+xml,%3Csvg xmlns='...'%3E...");
}
URL-encoded SVGs are often smaller than their Base64-encoded equivalents because SVG is already text. Base64 adds 33% overhead, while URL encoding only escapes special characters. Tools like SVGOMG can optimize SVGs before embedding.
Performance guidelines:
- Embed assets under 4KB as Base64 in CSS. Larger assets should be separate files.
- Embedded fonts increase initial CSS parse time. If your font file is over 50KB, serve it as a separate file with proper cache headers.
- If the CSS file containing Base64 data is render-blocking, the added size directly impacts First Contentful Paint. Consider moving non-critical embedded assets to a separate, async-loaded stylesheet.
- Build tools can automate the threshold: Vite, Webpack, and PostCSS plugins can inline assets below a configurable size limit.
Common mistake: Embedding the same Base64 image in multiple CSS rules. Extract it into a CSS custom property or a shared class to avoid bloating the stylesheet with duplicate data.
Use Case
Inlining small SVG icons as Base64 data URIs in a component library's CSS to create a zero-dependency icon system that works without any asset pipeline.