-
SVGs are great for symbolic imagery like icons.
- Icons don’t require fine detail
- They work in a variety of sizes
- SVGs are vector (that’s the “V”) images, which means they can be re-rendered at nearly any size
-
How do you use them in a website?
- There are a few ways: an tag,
<object>or<iframe>(not a good one), or the two realistic ways. - Completely inline, where the entire
<svg>...</svg>file is placed into the structure of the HTML - Or using a reference, where you have an svg made of up multiple sprites and then each one is actually shown in the DOM by referencing it using
<svg><use href="path/to/sprite.svg#foo"/></svg>. - Or you can even use them a favicon (except Safari, sigh).
- There are a few ways: an tag,
-
So which one should you use?
- Inline is just fine, unless you’re going crazy (like you have 1000 on a single page.) At that point you’re likely to have reused the same SVG and can save a little bandwidth by dedupeing them using
<use>method.- However, that amount saved is probably not going to be particularly significant. Gzip compression of responses will cut down a lot of that. You are using compression, yeah?
- Tyler Sticka in a Cloudfour article goes into depth on the variety of different techniques available. (Archived copy.)
- Inline is just fine, unless you’re going crazy (like you have 1000 on a single page.) At that point you’re likely to have reused the same SVG and can save a little bandwidth by dedupeing them using
-
Accessibility matters a lot here, too!
- It depends on exactly what you’re doing with the icon, but preferably you’re combining the icon with text, and not relying on an icon alone (which can lead to a wide variety of different interpretations) or text alone (it’s just boring!).
- Assuming that, this is a good base:
<a href="link"> <svg aria-hidden="true"> <!-- or the whole image here if you're doing inline --> <use xlink:href="/assets/icons.svg#foobar"></use> </svg> Go to foobar </a> ``` -
References
- https://css-tricks.com/accessible-svg-icons/
- https://css-tricks.com/accessible-svgs/
- https://cloudfour.com/thinks/svg-icon-stress-test/
- https://evilmartians.com/chronicles/how-to-favicon-in-2021-six-files-that-fit-most-needs
- https://caniuse.com/link-icon-svg
- There are a ton of SVG icon sets out there, check out Icon Libraries for some that I like.