Using Data URIs for Inline Images in HTML
Learn how to embed images directly in HTML using data URIs in img tags. Covers PNG, JPEG, GIF, and WebP with practical examples and size guidelines.
Detailed Explanation
Embedding Images with Data URIs
Data URIs let you embed images directly into HTML <img> tags, eliminating a separate HTTP request for each image. This is particularly effective for small, frequently-used images like icons, avatars, and UI elements.
Basic Syntax
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Small icon" />
The browser decodes the Base64 string and renders the image exactly as if it were loaded from an external URL.
Supported Image Formats
| Format | MIME Type | Best For |
|---|---|---|
| PNG | image/png |
Icons, logos, screenshots with transparency |
| JPEG | image/jpeg |
Photos, complex images without transparency |
| GIF | image/gif |
Simple animations, very small graphics |
| WebP | image/webp |
Modern format with better compression |
| SVG | image/svg+xml |
Scalable vector graphics |
Size Guidelines for Inline Images
- Under 2 KB: Always inline — the HTTP request overhead exceeds the Base64 overhead
- 2-10 KB: Usually beneficial to inline, especially for above-the-fold images
- 10-32 KB: Consider inlining only for critical render path images
- Over 32 KB: Use external files with proper caching instead
Performance Considerations
Inlined images cannot be cached independently by the browser. Every time the HTML page is loaded, the image data is re-downloaded as part of the document. This makes inlining counterproductive for large images or images shared across multiple pages. However, for small one-off images, the savings from eliminating an HTTP roundtrip (typically 50-200ms on mobile networks) outweigh the caching disadvantage.
Responsive Images and Data URIs
Data URIs work with the srcset attribute, but this is rarely practical since embedding multiple sizes as Base64 dramatically increases the HTML size. For responsive images, external files with srcset and sizes attributes are the better approach.
Use Case
You are building a single-page application with dozens of small UI icons (16x16 and 24x24 pixels) and want to eliminate the waterfall of HTTP requests that occurs when loading them as separate files.