Convert SVG to CSS Data URI: Encoding Steps
Converting raw SVG XML into a CSS data URI allows you to embed vector
graphics directly into stylesheets, eliminating extra HTTP requests.
This process involves preparing the XML markup, ensuring proper
namespace declarations, encoding unsafe characters for URL compatibility
(or converting to Base64), and constructing the proper
data:image/svg+xml URI scheme for use within CSS properties
like background-image.
Step 1: Optimize and Prepare the SVG Markup
Before encoding, clean up the raw SVG to reduce size and prevent
syntax errors: - Remove XML declarations (e.g.,
<?xml version="1.0" ... ?>), doctypes, and editor
metadata. - Ensure the root <svg> tag contains the
standard XML namespace attribute:
xmlns="http://www.w3.org/2000/svg". Browsers will not
render the SVG in CSS without this attribute. - Ensure all attribute
values use consistent quotation marks (preferably single quotes
' to minimize escaping issues in CSS).
Step 2: Choose an Encoding Approach
You can encode SVGs into CSS using either Percent-Encoding (URL Encoding) or Base64 Encoding: - Percent-Encoding (Recommended): Results in smaller file sizes, remains human-readable, and compresses significantly better with Gzip/Brotli. - Base64 Encoding: Guarantees universal compatibility without character-escaping issues but increases file size by roughly 33%.
Step 3: Perform Percent-Encoding (URL Encoding)
If using percent-encoding, you do not need to encode every
character—only characters that have special meaning in URLs or CSS: 1.
Hash/Octothorpe (#): Must be encoded as
%23. This is critical because # denotes a URL
fragment identifier and will break color definitions like
fill="#ff0000". 2. Quotes (" or
'): Replace double quotes with single quotes
inside the SVG attributes, or encode double quotes as %22.
3. Angle Brackets (< and
>): Replace < with
%3C and > with %3E. 4.
Whitespace and Line Breaks: Remove newlines and tabs,
or replace spaces with %20. 5. Ampersand
(&): Encode as %26.
Step 4: Construct the CSS Data URI
Once the markup is encoded, wrap it in the CSS url()
function using the proper MIME type and charset declaration.
Percent-Encoded Syntax:
.icon {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%23333' d='...'/%3E%3C/svg%3E");
}Base64 Syntax: If choosing Base64, convert the entire raw SVG string into a Base64 string and format it as follows:
.icon {
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCI+PHBhdGggZmlsbD0iIzMzMyIgZD0iLi4uIi8+PC9zdmc+");
}