There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions —
:focus, class name change, etc. — is different.
Let’s look at the ways.
Inline SVG is my favorite way to use SVG anyway, in part because of how easy it is to access and style the SVG.
If you’re used to working with icon fonts, one thing you might enjoy about them is how easy it is to change the color. You’re largely limited to a single color with icon fonts in a way that SVG isn’t, but still, it is appealingly easy to change that single color with
color. Using inline SVG allows you to set the
fill, which cascades to all the elements within the SVG, or you can fill each element separately if needed.
SVG Symbol / Use
There is such thing as an SVG sprite, which is a group of SVGs turned into
<symbol> elements such that any given icon can be referenced easily with a
You can still set the fill color from outside CSS rather easily this way, but there are caveats.
- The internal SVG elements (like the
<path>) can have no fill themselves. This allows the fill set from the parent SVG to cascade into the Shadow DOM created by
<use>. As soon as you have something like
<path fill="blue" ... />in the
<symbol>, you’ve lost outside CSS control.
- Likewise, the
fillof individual elements cannot be controlled within the SVG like you could with inline SVG. This means you’re pretty firmly in single-color territory. That covers most use cases anyway, but still, a limitation nonetheless.
SVG background images
SVG can be set as a background image just like PNG, JPG, …