SVG icons in HTML and CSS: four ways and when to use each
SVG is the right format for icons on the web: tiny, sharp at every pixel density and colorable with CSS. There are four ways to use one, and each has a job.
1. Inline SVG: colorable and accessible
Paste the markup into the HTML. The icon follows the text color through currentColor, can be animated with CSS and can carry a title for screen readers.
<button class="btn">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="…"/>
</svg>
Launch
</button>Use it for buttons, navigation and anything that changes color on hover. Run the file through the SVG optimizer first so the markup is short.
2. img tag: simple and cached
<img src="/icons/rocket.svg" width="20" height="20" alt="">The browser caches the file and the HTML stays small. The icon can't be recolored with CSS, so download it in the color you need. Give decorative icons an empty alt; give meaningful ones a short description.
3. CSS background or mask
A background-image shows the icon as is; a mask-image paints it with the element's background-color, so one file serves every color.
.icon-rocket {
width: 20px; height: 20px;
background-color: currentColor;
mask: url("/icons/rocket.svg") center / contain no-repeat;
}The SVG to data URI tool turns a file into a one-line url(...) you can paste into CSS with no extra request.
4. Sprite: many icons, one request
Combine the set into one sprite.svg and reference each icon by id:
<svg width="20" height="20"><use href="/sprite.svg#icon-rocket"/></svg>The SVG sprite tool builds the file and a demo page. Icons drawn with use follow currentColor like inline SVG.
| Way | Colorable with CSS | Cached | Best for |
|---|---|---|---|
| Inline | Yes | No | Buttons, nav, animated icons |
| img | No | Yes | Content images, emails |
| Mask | Yes | Yes | Icon fonts replacement |
| Sprite | Yes | Yes | Large sets |
Tip: Keep the viewBox and drop width and height from the file (the optimizer's Remove dimensions option), then size icons with CSS.
Favicons
A favicon is a special case: browsers want an .ico plus PNGs and a manifest. The favicon generator makes the whole set from one SVG.