Embedding Placeholder Images as Data URIs
Learn how to embed placeholder images as data URIs in HTML, CSS, and JavaScript. Covers base64 encoding, size considerations, and best practices for inline images.
Detailed Explanation
Embedding Placeholder Images as Data URIs
A data URI encodes an image directly into a text string that can be used anywhere a URL is expected — in HTML src attributes, CSS background-image properties, or JavaScript variables. This eliminates the need for separate image files.
Data URI Format
data:[mediatype];base64,[data]
Example:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...
Usage in HTML
<img
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
width="300"
height="200"
alt="Placeholder"
/>
Usage in CSS
.placeholder {
background-image: url('data:image/svg+xml;charset=UTF-8,...');
background-size: cover;
}
Usage in JavaScript
const img = new Image();
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...';
document.body.appendChild(img);
SVG Data URIs (Most Efficient)
For simple placeholder images, SVG data URIs are the most efficient option:
<img src="data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22300%22%20height%3D%22200%22%3E%3Crect%20width%3D%22300%22%20height%3D%22200%22%20fill%3D%22%23ccc%22%2F%3E%3C%2Fsvg%3E" />
This is a complete 300×200 gray placeholder in under 200 characters, with no base64 encoding needed.
Size Considerations
Base64 encoding increases file size by approximately 33%:
| Original Image | File Size | Base64 Data URI Size |
|---|---|---|
| 100×100 PNG | ~1.5 KB | ~2 KB |
| 300×200 PNG | ~5 KB | ~6.7 KB |
| 800×600 PNG | ~20 KB | ~26.7 KB |
| 300×200 SVG | ~0.2 KB | ~0.3 KB (URL-encoded) |
When to Use Data URIs
Good for:
- Small placeholder images (under 5KB)
- Single-use images that don't benefit from caching
- CSS sprites replacement for tiny icons
- Inline prototyping and code demos
Avoid for:
- Large images (over 10KB) — bloats HTML/CSS file size
- Repeated images — a cached file URL is more efficient
- Images that change frequently — cache invalidation doesn't work with data URIs
Use Case
Developers embedding placeholder images directly into component code, CSS custom properties, or JavaScript modules use data URIs to avoid managing separate image files during prototyping. This is particularly common in component libraries and Storybook stories.