Data URI Scheme Explained
Understand the data URI scheme for embedding files inline in HTML and CSS. Learn the syntax, MIME types, Base64 encoding, and browser support details.
Detailed Explanation
A data URI (also called a data URL) is a URI scheme that allows you to embed file content directly inline within web documents. Instead of pointing to an external file, the URI contains the actual data, encoded as either plain text or Base64.
Syntax:
data:[<mediatype>][;base64],<data>
data:-- the scheme identifier (required).<mediatype>-- the MIME type of the data, such asimage/png,text/html, orapplication/pdf. Defaults totext/plain;charset=US-ASCIIif omitted.;base64-- an optional flag indicating the data is Base64-encoded. Without this flag, the data is expected to be URL-encoded text.<data>-- the actual content, either URL-encoded or Base64-encoded.
Examples:
<!-- Plain text -->
<a href="data:text/plain;charset=utf-8,Hello%20World">Download</a>
<!-- Base64-encoded PNG image -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg..." />
<!-- Base64-encoded SVG -->
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0i..." />
<!-- Inline CSS font -->
@font-face {
font-family: 'MyFont';
src: url(data:font/woff2;base64,d09GMgABAA...) format('woff2');
}
Browser support: All modern browsers support data URIs. However, there are practical size limits. Internet Explorer 8 had a 32KB limit. Modern browsers can handle several megabytes, but performance degrades significantly with large data URIs because the content cannot be cached independently and must be parsed inline.
Security considerations: Some browsers restrict data URIs in certain contexts. For example, Chrome blocks top-level navigation to data: URIs (you cannot type a data URI into the address bar for HTML content). Data URIs in <script> tags may be blocked by Content Security Policy (CSP) directives.
When to use data URIs:
- Small assets (under 10KB) to reduce HTTP requests.
- Single-file HTML documents that must be self-contained.
- CSS sprites replacement for small icons.
- Email templates where external resources are unreliable.
Use Case
Creating self-contained HTML email templates where all images are embedded as data URIs to ensure they display correctly regardless of the recipient's email client settings.