How to Embed SVG Data URI in CSS Background Image

Embedding Scalable Vector Graphics (SVG) directly into CSS using data URIs allows you to display resolution-independent vector graphics without triggering separate HTTP requests. This technique reduces server round-trips, improves rendering performance for small icons, and keeps styling assets self-contained. This guide covers the syntax, encoding methods (URL-encoding and Base64), and critical requirements for using SVG data URIs inside the CSS background-image property.

The Basic Data URI Syntax

A data URI consists of a scheme (data:), a MIME type (image/svg+xml), optional encoding parameters (such as charset=utf-8 or ;base64), and the SVG data itself.

The generic format inside CSS is:

.element {
  background-image: url('data:image/svg+xml;utf8,<svg-content>');
}

Using raw or URL-encoded SVG text is generally preferred over Base64. It results in a smaller file size (Base64 adds roughly 33% overhead) and allows the markup to remain partially human-readable and editable directly within the stylesheet.

Requirements for Plain Text/URL Encoding:

  1. Namespace Attribute: The root <svg> tag must include the XML namespace: xmlns="http://www.w3.org/2000/svg". Without this, modern browsers will fail to render the image.
  2. Escaping Special Characters: Certain characters must be percent-encoded to prevent CSS parsing errors:
    • # must be encoded as %23 (crucial for hex colors like #ffffff becoming %23ffffff).
    • < should be encoded as %3C.
    • > should be encoded as %3E.
    • " (double quotes) should either be replaced with single quotes ' or encoded as %22 depending on the outer CSS wrapper quotes.

Example:

.icon-check {
  width: 24px;
  height: 24px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23007acc'%3E%3Cpath d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z'/%3E%3C/svg%3E");
}

Method 2: Base64-Encoded SVG

Base64 encoding converts the entire SVG markup into an ASCII string. While it prevents syntax issues with quotes and special characters, it increases the payload size and removes readability.

Example:

  1. Original SVG:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#ff0000">
  <circle cx="12" cy="12" r="10" />
</svg>
  1. Base64 String: PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmMDAwMCI+PGNpcmNsZSBjeD0iMTIiIGN5PSIxMiIgcj0iMTAiIC8+PC9zdmc+

  2. CSS Implementation:

.icon-circle {
  width: 24px;
  height: 24px;
  background-repeat: no-repeat;
  background-image: url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmMDAwMCI+PGNpcmNsZSBjeD0iMTIiIGN5PSIxMiIgcj0iMTAiIC8+PC9zdmc+');
}

Best Practices