[TUTORIAL] 6 min read

[TUTORIAL] Embedding Images with Base64

A complete tutorial on how to embed images directly into your HTML and CSS using Base64 data URIs.

September 2025 | web-dev

// What are Data URIs?

A data URI is a scheme that allows you to embed small files, like images, directly into your HTML or CSS. It's a way of including a file's content in the document itself, rather than linking to an external file.

The format of a data URI for a Base64-encoded image is: `data:[MIME_type];base64,[data]`

// How to Embed an Image in HTML

To embed an image in HTML, you can use the `` tag with the data URI as the `src` attribute:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA..." alt="A Base64-encoded image">

// How to Embed an Image in CSS

You can also embed images in CSS using the `url()` function:

.my-element {
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...");
}

// Pros and Cons

**Pros:**

- **Reduced HTTP requests:** Since the image is embedded, the browser doesn't need to make a separate request to fetch it. This can improve performance for small images.

- **Portability:** The HTML or CSS file is self-contained, which can be useful for things like email templates.

**Cons:**

- **Increased file size:** Base64 encoding increases the size of the image data by about 33%.

- **Caching:** Data URIs are part of the document, so they can't be cached separately by the browser.

- **Readability:** Large Base64 strings can make your code harder to read.

// When to Use Base64 Image Embedding

Base64 embedding is best for very small images, like icons or logos, where the overhead of an HTTP request is significant. For larger images, it's almost always better to use a separate, cacheable image file.