0

Background

I have recently read an article which talks about self-hosting your static assets and explains the risk of using CDN's or external infrastructure. This got me to think on hosting fonts & icons myself.

I'm aware that you can self-host fonts by downloading a font and using the file-path as a URL - to include that in your CSS. And you can also download or create an SVG for any icon and use it as a HTML element.

Question

But is it possible to use a self-hosted SVG in a CSS pseudo element like in the content property :before and :after? Similar to how Font Awesome allows you to mention content code for their icons

Note: My main intention is re-usability of same SVG in multiple CSS classes

Gangula
  • 5,193
  • 4
  • 30
  • 59

1 Answers1

1

Yes, through the data URIs; using the brackground or content property.

.icon::before {
  display: inline-block;
  content:'';
  width: 24px;
  height: 24px;
}

.icon-menu::before {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%280, 0, 0, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
<!doctype html>
<html>
    <head>
        <title>Developer</title>
    </head>
    <body>
        <div class="icon icon-menu"></div>
    </body>
</html>
  • Thank you for the answer @Andres. My main intention is re-usability. This way I would have to copy paste the URI in every class. And preferably, I'm looking for a way to use SVG in the CSS content property as a content code. – Gangula Oct 24 '21 at 07:02