How to change SVG color inside <use> element

The <use> element is very useful to prevent duplication of SVGs, but it is harder to style because it generates a shadow DOM that some CSS selectors can't reach.

There is a way to bypass this restriction tho !

Before

Your svg definition probably look like this :

<symbol id="icon-check" viewBox="0 0 24 24">
  <path
    d="M9 16.172l10.594-10.594 1.406 1.406-12 12-5.578-5.578 1.406-1.406z"
    fill="#000000"
    stroke="#000000"
  />
</symbol>

It has built-in colors and nothing happens when you change them :


svg {
  fill: yellowgreen;
  stroke: yellowgreen;
}



After

The solution is to set the color properties to currentColor inside your SVG definition :

<symbol id="icon-check" viewBox="0 0 24 24">
  <path
    d="M9 16.172l10.594-10.594 1.406 1.406-12 12-5.578-5.578 1.406-1.406z"
    fill="currentColor"
    stroke="currentColor"
  />
</symbol>

Now, the SVG color depends on it's parent color CSS property value :


svg {
  color: yellowgreen;
}

Awesome !


Side notes

What I also like about this technique is that (by default) your SVGs will inherit the text color of where you put it. So if you have different backgrounds + text color combos, the SVG will adapt itself automaticly :

lorem ipsum dolor sit amet consectetur elit
lorem ipsum dolor sit amet consectetur elit
lorem ipsum dolor sit amet consectetur elit

And it's possible to make color variants using opacity :


svg {
  color: yellowgreen;
  stroke-opacity: 0.5;
  stroke-width: 3;
}