Skip to content

SVG Encode Function

Tommy Hodgins edited this page Sep 28, 2019 · 1 revision

A custom function that can encode an SVG file referenced by its relative file path, and replaces it with the most efficiently encoded data URL to embed the SVG data inline in CSS

Syntax

--svg-encode(<path to file>)
  • <path to file> is a relative path to the SVG file

Usage

Use --svg-encode() anywhere a background image could be used in CSS to automatically convert it to url() with the encoded image data inside

Input

html {
  background: --svg-encode(assets/logo.svg)
}

Output

html {
  background: url(data:image/svg+xml, <encoded svg>)
}

Note: It also works with unquoted --svg-encode(), single-quoted --svg-encode('') or double-quoted --svg-encode("") URLs

More Info

Check out the blog post Optimizing SVGs in data URIs from Taylor Hunt