I wish to build a website where icon colors can be easily changed with the only change of the css. I've been given a set of custom icons in form of svg files.
I've already experimented with background color, filters and alike (see https://codesandbox.io/s/exciting-montalcini-xfufu?file=/index.html).
Which is the best technique to use? Should I generate a font from the SVGs?
First, open your SVG file and change the style of the .cls-1
path:
.cls-1 { fill: currentColor; }
Now place the SVG inside your HTML code. The color of the shield will follow the current font color. The <use>
tag will allow you to duplicate it easily. Just make sure to hide the original instance of the SVG with style="display: none;"
.
svg {
width: 42px;
height: 50px;
}
.green-icon { color: green; }
.red-icon { color: red; }
.blue-icon { color: blue; }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 768.42 907.1" style="display: none;"><defs><style>.cls-1{fill:currentColor;}.cls-2{fill:#fff;}</style></defs><g id="Livello_2" data-name="Livello 2"><g id="Layer_1" data-name="Layer 1"><path class="cls-1" d="M766.27,141.2c-157.6,0-279.1-44.3-382.5-141.2C282,97.7,160.47,141.2,2.07,141.2c0,253.7-53.4,618.2,382.5,765.9C820.47,758.6,766.27,394.9,766.27,141.2Z"/><path class="cls-2" d="M449.87,436.6a43.42,43.42,0,0,1,28.9-7.1l113.9-114-63.8-63.8L415,365.7a42.67,42.67,0,0,1-7.4,29.2Z"/><polygon class="cls-2" points="251.17 575.4 246.97 571.3 225.37 588.8 188.97 646.1 198.37 655.4 255.67 619 273.17 597.5 268.97 593.3 341.47 520.8 323.47 503.1 251.17 575.4"/><path class="cls-2" d="M350.27,374.5a88.86,88.86,0,0,0-108.9-109.8l50.4,50.3-13.2,49.3-49.4,13.2-50.3-50.3a88.86,88.86,0,0,0,113.5,107.7l.3.3,207.1,207.1a42,42,0,0,0,59.4-59.4Zm182.8,261a16,16,0,1,1,16.1-16A16,16,0,0,1,533.07,635.5Z"/></g></g></svg>
<svg class="green-icon" viewBox="0 0 768.42 907.1"><use href="#Layer_1"></use></svg>
<svg class="red-icon" viewBox="0 0 768.42 907.1"><use href="#Layer_1"></use></svg>
<svg class="blue-icon" viewBox="0 0 768.42 907.1"><use href="#Layer_1"></use></svg>
(This solution is based on this article from CSS Tricks.)