Icons SVG as Icons
SVG icons can be added to a page as an image file or pasted directly into the HTML, and only that second option - inline SVG - lets CSS control the icon's fill and stroke color.
Using SVG Directly as Icons
SVG (Scalable Vector Graphics) describes a picture as a set of shapes and paths rather than a grid of colored pixels. An icon built in SVG is really just a very small drawing, and because that drawing is described in markup, it can either be linked in like a normal picture or written straight into the page's HTML.
Three Ways to Place an SVG
- As an <img> source, the same way you'd reference a PNG or JPEG file.
- As a CSS background-image, useful for purely decorative icons.
- Inline, by pasting the <svg>...</svg> markup directly into the HTML.
Only the inline option puts the icon's shapes directly into the page's DOM. When an SVG is referenced through img or background-image, the browser treats the file as a sealed image - your page's CSS cannot reach inside it, even if the SVG file itself is just text.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="/icons/heart.svg" width="24" height="24" alt="Favorite">
</body>
</html>Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 21s-6.7-4.35-9.5-8.5C.7 9.2 2 5 6 5c2.1 0 3.6 1.2 4.5 2.8C11.4 6.2 12.9 5 15 5c4 0 5.3 4.2 3.5 7.5C18.7 16.65 12 21 12 21z"/>
</svg>
</body>
</html>Because this heart is inline, it is part of the page just like any <div> or <p>, so ordinary CSS selectors can target its fill and stroke - something no img-based icon allows.
When to Choose Inline SVG
- You need per-instance colors, like a red, yellow, or green status dot built from the same shape.
- You want to animate or highlight part of the icon on hover or focus.
- You want to skip an extra network request for a handful of tiny icons.
- You need custom accessibility text, using a <title> element inside the SVG itself.