Add inline SVG directly in your CSS
Sometimes, you don’t get much control of the HTML, so being able to add something like an SVG icon, directly in your CSS is handy.
Luckily, CSS has us covered (pun-intended), with background-image
and data URIs.
- Code language
- CSS
p::before {
content: '';
background-image: url('data:image/svg+xml;utf8,<svg fill="%23e67e22" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M14 9.5c0-.825.675-1.5 1.5-1.5h1c.825 0 1.5.675 1.5 1.5v1c0 .825-.675 1.5-1.5 1.5h-1c-.825 0-1.5-.675-1.5-1.5v-1zM20 24h-8v-2h2v-6h-2v-2h6v8h2z"/><path d="M16 0C7.163 0 0 7.163 0 16s7.163 16 16 16 16-7.163 16-16S24.837 0 16 0zm0 29C8.82 29 3 23.18 3 16S8.82 3 16 3s13 5.82 13 13-5.82 13-13 13z"/></svg>');
width: 1.2em;
height: 1.2em;
background-size: cover;
display: block;
}
There’s some quirks with this approach—sure, but it’s a pretty handy approach to lean into if you need it. Just be aware that setting colour, like fill
is a bit fiddly. In the above example, I’ve escaped the #
of the hex code as %23
.
If you set your background-size
as cover, you get way more control of the sizing of your SVG, too. It allows you to leverage some relative sizing with EM units, for example.
I would personally stray away from this method—instead, opting for inline SVG where possible. It gives a bit more control of things, overall—especially in terms of accessibility.
To learn more about how all of this works, I would strongly recommend that you watch this talk by CSS legend, Lea Verou.