Bootstrap Icons as CSS variables
Using icon fonts in HTML markup is still very popular, despite their many drawbacks. Using them means even if you only use a single icon, you still need to load the font file and the CSS for that entire icon set which can be a relatively significant performance overhead. Many sites are loading icon fonts from third-party CDNs too which can be blocked by users content blockers.
In fact, CSS Tricks did an Inline SVG vs Icon Fonts Cagematch article 12 years ago (!) which concluded that inline SVGs are a better choice for icons, and in fact since then the benefits of avoiding icon fonts have only grown.
I can see the appeal of using icon fonts, though, if you’re using Bootstrap Icons for example.. just use markup like:
<i class="bi bi-heart"></i>There’s a better way though! Instead of using icon fonts, we can set all the icons we need as CSS variables and then map them to a CSS class - so we can use them in a similar way to the webfonts but without the extra file downloads and the other drawbacks.
I’ve released Bootstrap Icons as CSS variables, a small project that exposes Bootstrap Icons as CSS custom properties.
So you have access to the icon as a CSS variable like this:
--bi-hearts: url("data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"currentColor\" viewBox=\"0 0 16 16\"><path fill-rule=\"evenodd\" d=\"M4.931.481c1.627-1.671 5.692 1.254 0 5.015-5.692-3.76-1.626-6.686 0-5.015m6.84 1.794c1.084-1.114 3.795.836 0 3.343-3.795-2.507-1.084-4.457 0-3.343M7.84 7.642c2.71-2.786 9.486 2.09 0 8.358-9.487-6.268-2.71-11.144 0-8.358\"/></svg>");and a class to reference it:
.bi-heart {
mask-image: var(--bi-heart);
}So your HTML markup is identical to using icon fonts:
<i class="bi-heart"></i>You can size the icon with CSS like so:
<i class="bi-heart" style="height: 2rem; width: 2rem;"></i>The package includes the generated CSS - with both CSS variables and class names referencing the CSS variables as SVG masks.
mask-image is supported unprefixed in all modern browsers (Chrome 120, Safari 15.4, Firefox 53 — caniuse). To widen support further (Safari 4.0+, Opera), you can use Autoprefixer to automatically add -webkit-mask-image prefix (alongside mask-image). Because this uses CSS variables, the same variables are referenced from :root without increasing filesize much. Neat!
The stylesheet is approx 1.3 MB (~230 KB gzipped) and includes all 2078 icons. You can reduce file size and improve performance by only including the CSS (or variables) for the icons you need.
- Demo & examples: https://coliff.github.io/bootstrap-icons-css/
- GitHub repository: https://github.com/coliff/bootstrap-icons-css/
- npm package: https://www.npmjs.com/package/bootstrap-icons-css