How to Embed an SVG in CSS
Recently, I needed to use an SVG as a background image in CSS. I didn’t want to host the SVG somewhere, so I couldn’t just link to it. I did have access to the SVG source, so I wondered if I could embed it. As I quickly found out, you can use a data URL.I use CSS data URLs to embed the fonts I use for this website. I didn’t know they could be used for SVGs too. Here’s an example on MDN doing just that.I initially learned how to do this from this stack overflow post.
Embedding a specific SVG
Let’s work through an example with this SVG triangle:
The SVG source looks like:
<svg xmlns="http://www.w3.org/2000/svg"
width="150" height="150"
viewBox="0 0 203 203"
fill="none">
<polyline points="100,3 200,200 3,200 100,3"
fill="none" stroke="pink" stroke-width="3"/>
</svg>
SVG Data URL
The general format for an SVG data url is:
data:image/svg+xml;utf8,[some actual SVG here]
So in theory we could paste our SVG from above like this:If you paste this into the browser bar in Firefox, it renders the pink triangle.
data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="150" height="150" viewBox="0 0 203 203" fill="none"><polyline points="100,3 200,200 3,200 100,3" fill="none" stroke="pink" stroke-width="3"/></svg>
However, to use the CSS url()
function, we need to enclose the data URL in double quotes ""
, which means that our SVG needs to use single quotes:
background-image: url(
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='150' height='150' viewBox='0 0 203 203' fill='none'><polyline points='100,3 200,200 3,200 100,3' fill='none' stroke='pink' stroke-width='3'/></svg>"
);
Additionally, any SVG content needs to be URL escaped, for example #
used for SVG colors need to be replaced with %23
.My example triangle doesn’t have any, but this replacement proved vital for my actual use case.
To be safe, you could URL escape the entire SVG, which is what MDN does in this example.In practice, I didn’t need to escape the SVG tags for my use case rendered in Firefox.
With that, we now have the ability to inline SVGs in CSS.