Data URI Basics and Syntax Explained
Learn the complete data URI syntax: the data: scheme, media type, base64 parameter, and encoded payload. Understand when and how to use data URIs in web development.
Detailed Explanation
Understanding the Data URI Scheme
A data URI (Uniform Resource Identifier) is a way to embed file content directly into a document using the data: scheme. Unlike traditional URLs that point to a remote server, a data URI contains the actual data inline. The formal syntax is:
data:[<mediatype>][;base64],<data>
Breaking Down the Components
data:— The URI scheme identifier. This tells the browser that the following content is inline data, not a URL to fetch.<mediatype>— An optional MIME type string such astext/plain,image/png, orapplication/json. If omitted, the default istext/plain;charset=US-ASCII.;base64— An optional flag indicating the data is Base64-encoded. Without this flag, the data is expected to be percent-encoded (URL-encoded).,<data>— The actual content, either Base64-encoded binary or percent-encoded text.
Examples of Valid Data URIs
A simple text data URI:
data:text/plain;charset=utf-8,Hello%20World
A Base64-encoded PNG pixel:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==
When to Use base64 vs Percent-Encoding
For text content like HTML, CSS, or SVG, percent-encoding can sometimes produce a smaller result since printable ASCII characters pass through unchanged. For binary content like images, audio, or fonts, Base64 is required because percent-encoding binary bytes is extremely verbose (each byte becomes three characters like %FF).
Data URIs in the RFC
Data URIs are defined in RFC 2397, published in 1998. Despite their age, they remain widely supported in all modern browsers and are commonly used for performance optimization by reducing HTTP requests.
Use Case
You are building a static HTML email template and need to understand the data URI format to embed a small logo without relying on an external image server that may be blocked by email clients.