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
p::before {
  content: '';
  background-image: url('data:image/svg+xml;utf8,<svg fill="%23e67e22" xmlns="" 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.

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.

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.