Styling SVG


Styling an SVG is simple:

<svg>
  <circle cx="20" cy="20" r="20" fill="red" />
</svg>

You can get the job done with plain, old CSS:

circle {
  fill: green;
}

Symbol

But what if we’re using an SVG symbol?

<svg style="display: none;">
  <symbol id="circle">
    <circle cx="20" cy="20" r="20" fill="red" />
  </symbol>
</svg>

<svg>
  <use class="green" xlink:href="#circle" />
</svg>

Unfortunately, the color doesn’t seem to be applied on the <use>:

.green {
  fill: green;
}

There are 2 approaches we can take here:

  1. remove the presentation attribute, or
  2. force the circle to inherit the fill color.

Presentation Attribute

Removing presentation attributes is pretty straightforward:

<svg style="display: none;">
  <symbol id="circle">
    <circle cx="20" cy="20" r="20" />
  </symbol>
</svg>

Now the fill color is applied. But the disadvantage of this approach is that you will need to specify the property for all <use> elements. With the attribute gone, there’s no more fallback.

Hence, the better solution is to force the property to be inherited.

Inherit Property

Here, you keep the SVG as it was before and add an additional CSS rule that allows the presentation attribute to be overridden:

circle {
  fill: inherit;
}

If you have multiple attributes, you can specify all:

circle {
  all: inherit;
}


Please support this site and join our Discord!