Quick Tip: SVG <use> Style Two Colors
Using SVGs as a icon sprite is gaining traction right now. Chris Coyier wrote about it many times. And even here on codepen this technique is used (just look in the devtools)
I wrote a grunt tasked called grunt-svgstore to auto generate such a SVG Sprite.
Usage
Everytime you want to use an icon you write
<svg class="icon IconName">
<use xlink:href="#iconId"></use>
</svg>
The Problem
Styling the icon with CSS is limited because you can't access elements inside the Shadow DOM created by the <use>
-tag.
Even the /deep/
combinator used to dive into Shadow DOM isn't working in Chrome Canary with SVGs (as time of writing).
You can track this issue here
The good part: It is possible to style one color of an icon using the fill
property:
But what if you want to style more than one color in an SVG?
currentColor
To The Rescue
Ever heard of the special currentColor
value? It's basically a CSS variable that contains the current color set by the color
property.
With that in mind we can use the fill
and color
property to change two colors inside the SVG icon.
Usecase
I found this little trick while creating this pen.
There I used the fill
property to controll the background circal and color
to color the S-Shape.
Future?
I think the /deep/ combinator is the way we will be doing this in the futur but untill than we have to work around this.