Last updated
Why Convert SVG to Base64?
Base64-encoding an SVG allows it to be embedded directly in CSS or HTML as a
data URI, eliminating an HTTP request. This is useful for small icons and
background images. The encoded SVG can be used as an img src,
CSS background-image, or content property value.
Data URI Format
data:[mediatype][;base64],data
SVG example:
data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjwvc3ZnPg==
URL-encoded alternative (smaller for SVG):
data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E
Converting in JavaScript
// SVG string to Base64 data URI
function svgToBase64(svgString) {
const encoded = btoa(unescape(encodeURIComponent(svgString)));
return `data:image/svg+xml;base64,${encoded}`;
}
// SVG string to URL-encoded data URI (often smaller than base64)
function svgToDataUri(svgString) {
const encoded = encodeURIComponent(svgString)
.replace(/'/g, '%27')
.replace(/"/g, '%22');
return `data:image/svg+xml,${encoded}`;
}
// Usage in CSS
const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="5" fill="red"/></svg>';
document.body.style.backgroundImage = `url("${svgToDataUri(svg)}")`;
Base64 vs URL Encoding
For SVG specifically, URL encoding is usually more efficient than Base64 because SVG is already mostly ASCII text. Base64 increases size by ~33%, while URL encoding only encodes special characters. Use Base64 when the SVG contains binary data or when the target context requires it (some older email clients).