09. SVG Patterns

The <pattern> element can be used to fill SVG elements with repeating shapes.
It can be a little confusing at first as the pattern element has it’s own coordinate system, but patterns are mega fun to experiment with.

You can also use other fill types within a pattern fill, which is pretty inception-y.
Here’s an example of using a gradient fill within a pattern!

This demo is working in three steps, let's break them down:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" preserveAspectRatio="xMidYMid slice">
	<defs>
		<linearGradient id="Gradient1">
			<stop offset="0%" stop-color="white" />
			<stop offset="100%" stop-color="#9474c8" />
		</linearGradient>

		<pattern id="Pattern" x="0" y="0" width="0.25" height="0.25" patternContentUnits="objectBoundingBox">
			<circle cx="0.125" cy="0.125" r="0.1" fill="url(#Gradient1)" />
		</pattern>
	</defs>

	<rect fill="url(#Pattern)" width="100%" height="100%" />
</svg>

Try resizing the svg to see how the pattern is being repeated

1. The gradient

First we define the gradient that we want to apply on the pattern.
In our case we are going to use a linear-gradient but there is also radial-gradient available.

The gradient is responsive and will automatically stretch based on the element we apply it on.

2. The pattern

We first decide on the width & height of our pattern. Everything inside the pattern bigger than those dimensions will be cropped.

In order to make the pattern coordinates system uses the bounding box of the element it's being applied to, we need to set the attribute patternContentUnits value to objectBoundingBox

The default value is userSpaceOnUse and indicates that all coordinates inside the pattern refer to the user coordinate system of the whole SVG.

You can think of your pattern as an SVG inside its parent SVG. You can add any element you want inside it and it will be duplicate along the pattern.
In the demo we are setting only a single circle, but you could have more.

To prevent our circles to touch each others when being repeated, we are setting their diameter just a little bit smaller than the width & height of the pattern.

3. Using the pattern

To apply the pattern on any SVG elements, you need to reference the id of the pattern in the fill="url(#Pattern)" attribute.

The pattern can also be applied on the stroke="url(#Pattern)" attribute if needed.