Coloring paths on external svg sprites
When using an inline svg sprite, besides applying a color it with fill
property, we can set a different color for each path:
<svg ... >
<symbol id="svg-inline-truck" ... >
<path id="svg-inline-truck_body" ... />
<path id="svg-inline-truck_cab" ... />
<path id="svg-inline-truck_wheels" ... />
</symbol>
</svg>
<svg>
<use xlink:href="#svg-inline-truck"></use>
</svg>
#svg-inline-truck_body { fill: red }
#svg-inline-truck_cab { fill: orange }
#svg-inline-truck_wheels { fill: blue }
Unfortunately, when using this same svg sprite as external asset, some browsers lose the ability to set a different color for each path:
- Safari
- Chrome
- Samsung Browser
However, there is a workaround, using CSS custom properties to achieve cross-browser svg path coloring, in a easy way:
<svg ... >
<symbol id="svg-external-truck" ... >
<path fill="var(--color-truck_body)" ... />
<path fill="var(--color-truck_cab)" ... />
<path fill="var(--color-truck_wheels)" ... />
</symbol>
</svg>
<svg class="svg-external-truck">
<use xlink:href="sprite.svg#svg-external-truck" />
</svg>
$color-truck_body: red;
$color-truck_cab: orange;
$color-truck_wheels: blue;
.svg-external-truck {
// Browsers that DO support custom properties
--color-truck_body: $color-truck_body;
--color-truck_cab: $color-truck_cab;
--color-truck_wheels: $color-truck_wheels;
// Browsers that DO NOT support custom properties
[fill="var(--color-truck_body)"] { fill: $color-truck_body }
[fill="var(--color-truck_cab)"] { fill: $color-truck_cab }
[fill="var(--color-truck_wheels)"] { fill: $color-truck_wheels }
}
If no color is applied, svg paths will remain black, by default.
Notes:
- Some browsers don't support external svg sprite assets, so you should ajax for the sprite.
- Serve external sprite from same domain as main document, to avoid cross-origin issues.
-
There is a simpler technique, limited to 2 different colors, using
fill="currentColor"
More info:
- SVG sprite viewer
- How SVG Fragment Identifiers Work
- Coloring SVGs in CSS Background Images
- 5 Gotchas You're Gonna Face Getting Inline SVG Into Production