Base64 Data URLs — Embed Images, Fonts, and Files in HTML and CSS
Base64 data URLs encode binary files as text strings for embedding directly in HTML, CSS, or JSON. Here's how data URLs work, the correct format, and when to use them vs...
A Base64 data URL embeds binary data directly in HTML, CSS, or JavaScript as a text string. Instead of referencing an external file with a URL, you encode the file’s bytes as base64 and inline it. This eliminates an HTTP request but increases payload size by ~33%.
Use the base64 encoder to encode files and generate data URLs.
Data URL format
data:[<mediatype>][;base64],<data>
Components:
data:— the scheme<mediatype>— MIME type (e.g.,image/png,text/plain,font/woff2);base64— indicates base64 encoding (omit for URL-encoded text)<data>— the actual encoded data
Examples:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0...
data:text/plain;charset=utf-8,Hello%20World
data:text/html,<h1>Hello</h1>
data:font/woff2;base64,d09GRgABAAAAAAhw...
Image data URLs
In HTML
<!-- Regular external image: -->
<img src="/images/logo.png" alt="Logo">
<!-- Embedded data URL: -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==" alt="Logo">
The browser renders both identically.
In CSS
/* Regular external background: */
.icon {
background-image: url('/images/icon.png');
}
/* Embedded data URL: */
.icon {
background-image: url('data:image/png;base64,iVBORw0KGgo...');
}
/* CSS :before with inline SVG: */
.check::before {
content: url('data:image/svg+xml;base64,PHN2Zy...');
}
SVG data URLs (without base64)
SVG is text — you can use URL encoding instead of base64 (smaller result):
/* URL-encoded SVG (no base64): */
.icon {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 2...'/%3E%3C/svg%3E");
}
/* Base64-encoded SVG (larger, but simpler to generate): */
.icon {
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxu...");
}
URL-encoded SVG is typically 10–15% smaller than base64-encoded SVG. For SVG specifically, prefer URL encoding.
Font embedding with data URLs
Inline a web font to eliminate a font request:
@font-face {
font-family: 'Inter';
src: url('data:font/woff2;base64,d09GRgABAAAAAAhw...') format('woff2');
font-weight: 400;
font-style: normal;
}
body {
font-family: 'Inter', sans-serif;
}
Caution: Web fonts can be 200KB–500KB. Embedding as base64 adds 33% overhead and inlines that data in your CSS. This often hurts performance more than it helps.
Generating data URLs in JavaScript
From a file input (browser)
function fileToDataUrl(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file); // Returns complete data URL
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
});
}
// Usage:
document.getElementById('fileInput').addEventListener('change', async (e) => {
const file = e.target.files[0];
const dataUrl = await fileToDataUrl(file);
// Use as image src:
document.getElementById('preview').src = dataUrl;
// Extract just the base64 data:
const base64 = dataUrl.split(',')[1];
// Get MIME type:
const mimeType = dataUrl.match(/data:([^;]+)/)[1];
});
From a URL (fetch + encode)
async function urlToDataUrl(imageUrl) {
const response = await fetch(imageUrl);
const blob = await response.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
const dataUrl = await urlToDataUrl('https://example.com/logo.png');
In Node.js
import fs from 'fs';
import path from 'path';
function fileToDataUrl(filePath) {
const buffer = fs.readFileSync(filePath);
const base64 = buffer.toString('base64');
const ext = path.extname(filePath).slice(1).toLowerCase();
const mimeTypes = {
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
png: 'image/png',
gif: 'image/gif',
webp: 'image/webp',
svg: 'image/svg+xml',
woff2: 'font/woff2',
woff: 'font/woff',
pdf: 'application/pdf',
};
const mimeType = mimeTypes[ext] || 'application/octet-stream';
return `data:${mimeType};base64,${base64}`;
}
const dataUrl = fileToDataUrl('./logo.png');
// "data:image/png;base64,iVBORw0KGgo..."
Data URL size and performance
Base64 encoding inflates file size by approximately 33%:
Original: 10,000 bytes (10KB PNG)
Base64: 13,333 bytes (33% larger)
Additional overhead: the data URL prefix itself (data:image/png;base64, = 22 chars).
When data URLs improve performance:
- Images smaller than ~5KB (HTTP request overhead exceeds size increase)
- Images in CSS that prevent render-blocking font loading
- Email HTML (images blocked by default — embedded images load)
- Self-contained HTML files for offline use
When data URLs hurt performance:
- Large images (hundreds of KB) — the encoding overhead + loss of caching outweighs the saved request
- Fonts — too large, lose caching
- Multiple uses of the same image — each use duplicates the full base64 string instead of sharing a cached file
- Critical rendering path — large inline data blocks delay HTML parsing
Related tools
- Base64 Tool — encode files and generate data URLs
- Base64 Image Encoding — image-specific guide
- Base64 Encode Online — encoding reference
Related posts
- Base64: How It Actually Works Under the Hood — Base64 is everywhere — in JWTs, data URLs, email attachments. This is the byte-l…
- When You Should NOT Use Base64 Encoding — Base64 is the duct tape of the web — and like real duct tape, it's used in place…
- Base64 Encoding on the Command Line — Linux, macOS, and Windows — Encode and decode Base64 on the command line using base64, openssl, and PowerShe…
- Base64 Encode Online — Encode Text and Files to Base64 Instantly — Base64 encoding converts binary data into printable ASCII text. It's used in ema…
- Base64 Image Encoding — Embed Images in HTML, CSS, and JSON — Base64 image encoding converts image files to text strings for embedding in HTML…
Related tool
Encode and decode Base64 strings and files. Client-side, safe for sensitive data.
Written by Mian Ali Khalid. Part of the Encoding & Crypto pillar.