2020/05/28

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:

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:

More info: