<pattern>
Defines a repeatable pattern to be used as a fill in an SVG tag on an HTML page.
The <pattern>
tag is used in SVG to define a pattern (pattern) that can be used to fill or outline other elements.
It allows you to create complex designs by repeating shapes, images, or patterns.
Structure and syntax of the <pattern>
tag
Structure
Here is a basic example:
HTML
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="dots" x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse">
<circle cx="5" cy="5" r="2" fill="blue" />
</pattern>
</defs>
<rect x="0" y="0" width="200" height="200" fill="url(#dots)" />
</svg>
In this example:
- The
<pattern>
tag defines a pattern calleddots
with itsid
attribute; - The pattern is a blue circle with a radius of 2 (
r
) that repeats every 10 pixels in width and height; - The pattern is applied as a fill to a rectangle with
fill="url(#dots)"
.
Here is the result:
Advanced example
Here is a more complex example using shapes and colors:
HTML
<svg width="300" height="300" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="diagonalStripes" width="10" height="10" patternUnits="userSpaceOnUse">
<rect width="10" height="10" fill="lightgray" />
<line x1="0" y1="10" x2="10" y2="0" stroke="red" stroke-width="2" />
</pattern>
</defs>
<rect x="0" y="0" width="300" height="300" fill="url(#diagonalStripes)" />
</svg>
In this example:
- A pattern with red diagonal stripes (
<line>
) is created on a light gray background (<rect>
in the<pattern>
tag); - The pattern is applied as a fill to a large rectangle with
fill
on the<rect>
tag.
Try it yourself:
Attributes of the <pattern>
tag
The <pattern>
tag handles several attributes:
Attribute | Description |
---|---|
id | Unique identifier of the pattern, used to reference it in other elements via fill="url(#id)" or stroke="url(#id)" . |
width , height | Dimensions of the pattern (by default in pixels). |
x , y | Initial position of the pattern. |
patternUnits | Coordinate system for the pattern (userSpaceOnUse or objectBoundingBox ). |
patternContentUnits | Specifies the coordinate system for the content of the pattern (userSpaceOnUse or objectBoundingBox ). |
viewBox | Defines a view box to scale the pattern content. |
preserveAspectRatio | Determines how to scale the pattern if its proportions do not match the element to which it is applied. |
Browser compatibility
The <pattern>
tag is widely supported by modern browsers:
Browser | Compatibility |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Internet Explorer | Partial (9+) |