Add inline SVG directly in your CSS

Categories


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.


Comments

If you liked this post, you might like these ones, too

  1. Use a set to remove array duplicates

    🔥 A handy quick tip.

    Continue
  2. Contains CSS attribute selector

    🔥 A handy quick tip.

    Continue
  3. CSS Logical Properties

    Create spacing that works regardless of the direction of your content or the environment of your users.

    Continue

Become a supporter by joining the Piccalilli Membership

For as little a $5 per month, you can get access to a private, friendly community, get a weekly newsletter and help to make as much content free as possible around here. If you join the $10 per month supporters club, you get access to premium tutorials and free access to mini courses!

Become a member

Sign up for updates

Stay up to date with updates from Piccalilli. You’ll get alerted as soon as any new content gets published. You’ll also get updates on upcoming courses and membership features! You can unsubscribe at any time, too.