SVG Gradients

We recently had a client who ran a WordPress site and wanted to use Font Awesome and other SVG’s within his content. One day he asked how to fill the SVG’s with a gradient so I sent him to the MDN docs for linear gradients and did a sample for him on the icon he asked about. He loved it, but quickly got bored because as it turns out, he wanted them on every SVG on his entire site. He was doing a lot of copy/paste work for each SVG. How tedious!

How to apply a gradient to all SVG’s

Step 1: Create an SVG definition with your desired gradients

I’ve created two types of gradients here. A linear gradient with an id of linear and a radial gradient with an id of radial. I’ve also added a class of svg-settings to the svg element itself so we can hide it later. The linear gradient has 2 stops that we’ll color with css, and the radial gradient has the stop-color directly on the stop. You can decide which method you prefer. You can place the following HTML anywhere inside the body.

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" class="svg-settings">
	<defs>
		<radialGradient id="radial">
			<stop offset="30%" stop-color="yellow" />
			<stop offset="95%" stop-color="orange" />
		</radialGradient>
		<linearGradient id="linear" gradientTransform="rotate(40)">
			<stop offset="0%" class="stop1"></stop>
			<stop offset="100%" class="stop2"></stop>
		</linearGradient>
	</defs>
</svg>

Step 2: Hide the SVG definition

We don’t want this SVG showing on the front-end. We’re only going to use its definition. Add this to your sites CSS.

.svg-settings {
	height: 0;
	width: 0;
	overflow: hidden;
	position: absolute;
}

Step 3: Using the gradients

You’ll need to target your SVG’s with CSS then simply fill with the id of the definition you wish to use.

svg {
	fill: url(#radial);
}
SVG's with radial gradient

If you were to use the linear gradient we’ve created, you’d need to also choose the stop colors. Let’s do something like this:

svg {
	fill: url(#radial);
}

.stop1 {
	stop-color: dodgerblue;
}

.stop2 {
	stop-color: blueviolet;
}

That’s it!

Targeting Font Awesome

To apply these rules to font awesome you’ll need to make sure you’re using Font Awesome SVG’s and not the web fonts. Then you’ll have to be a little more specific in your CSS.

.svg-inline--fa path {
	fill: url(#linear);
}

Changing the gradient direction

In the HTML block above where we define the definitions you will see a gradientTransform attribute. I’ve added a simple rotate to it. However, you can add any transformations listed on MDN. Please note that browser support is unknown.