SVG Pattern
Planted:
Status: decay
SVG elements (such as <rect>
or <circle>
) can be defined as children of the <pattern>
element.
Together, these children make a tile.
The pattern element's id
can be used as the fill
of an element, which will repeat the tile until the element is completely covered.
Number of Tiles
The width and height values of a <pattern>
element determines how many tiles of that pattern are rendered.
localhost:3000
<!-- Using -1 and 102 (instead of 0 and 100) to prevent cut-off of shapes' stroke positioned on the edge (example: 0, 0). --> <svg viewBox="-1 -1 302 502"> <defs> <!-- A pattern with width and height of 100%. Only 1 pattern tile will be rendered. --> <pattern id="myPattern1" viewBox="0 0 10 10" width="100%" height="100%"> <rect x="0" y="0" width="5" height="5" fill="hsl(0, 0%, 11%)" /> </pattern> <!-- A pattern with width and height of 10%. 10 pattern tiles will be rendered. --> <pattern id="myPattern2" viewBox="0 0 10 10" width="10%" height="10%"> <rect x="0" y="0" width="5" height="5" fill="hsl(0, 0%, 11%)" /> </pattern> </defs> <rect x="0" y="0" width="100" height="100" stroke="hsl(0, 0%, 50%)" fill="url(#myPattern1)" /> <rect x="0" y="108" width="100" height="100" stroke="hsl(0, 0%, 50%)" fill="url(#myPattern2)" /> <!-- Pattern applied to shape with different aspect ratio than pattern's aspect ratio. --> <rect x="0" y="216" width="140" height="100" stroke="hsl(0, 0%, 50%)" fill="url(#myPattern2)" /> </svg>
patternUnits
A pattern attribute that indicates which coordinate system to use for the <pattern>
element.
Value can be:
- ▪
objectBoundingBox
(default): the coordinate system defined on the pattern element. - ▪
userSpaceOnUse
: the user coordinate system (the coordinate system of the svg element using the pattern). This is like rendering the pattern in the background of the<svg>
. It is hidden and only parts of it are exposed by shapes that use the pattern.
Below is an example using userSpaceOnUse
.
Change the x
and y
values to move bottom square, showing how the pattern remains consistent with the other shapes.
localhost:3000
<svg viewBox="-1 -1 302 302"> <defs> <pattern id="myPattern" viewBox="0 0 30 30" width="30" height="30" patternUnits="userSpaceOnUse"> <polygon points="0 30 15 0 30 30" fill="hsl(0, 0%, 11%)" /> </pattern> </defs> <rect x="0" y="0" width="100" height="100" stroke="hsl(0, 0%, 50%)" fill="url(#myPattern)" /> <rect x="108" y="0" width="140" height="100" stroke="hsl(0, 0%, 50%)" fill="url(#myPattern)" /> <rect x="0" y="108" width="100" height="100" stroke="hsl(0, 0%, 50%)" fill="url(#myPattern)" /> </svg>

Misc.
- ▪
patternContentUnits
has no effect ifviewBox
is specified on the<pattern>
element. - ▪ to do:
patternTransform
- ▪ to do:
preserveAspectRatio