The <defs> tag is used in an SVG document to define elements that are not directly displayed, but can be reused within the SVG.
It is ideal for declaring definitions, such as:
- gradients;
- filters;
- or other graphical resources that you can apply later.
Use <defs> to centralize reusable styles and components in your SVG. Refactor: simplification! 😊
Â
Structure and syntax of the <defs> tag
Structure
Here is a simple example:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="myGradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="blue" />
<stop offset="100%" stop-color="red" />
</linearGradient>
</defs>
<rect width="200" height="200" fill="url(#myGradient)" />
</svg>In this example:
- The linear gradient is defined within
<defs>with anid(#myGradient); - It is then applied as a fill to the rectangle using
fill="url(#myGradient)".
Try it yourself:
Â
Example
Here is an example using multiple resources:
<svg width="300" height="300" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="myPattern" width="10" height="10" patternUnits="userSpaceOnUse">
<circle cx="5" cy="5" r="3" fill="blue" />
</pattern>
<filter id="blurFilter">
<feGaussianBlur in="SourceGraphic" stdDeviation="3" />
</filter>
</defs>
<rect width="300" height="100" fill="url(#myPattern)" />
<circle cx="150" cy="150" r="50" fill="green" filter="url(#blurFilter)" />
</svg>In this example:
- A pattern (
pattern) is created to fill the rectangle with blue circles; - A filter (
filter) applies a blur to a green circle.
Here is the result:
Â
Attributes
The <defs> tag does not have specific attributes, but it can contain any SVG element, such as:
Elements defined within <defs> become reusable with their id, for example via url(#id).
Â
Best practices
Here are some tips for effectively using <defs>:
- Place all reusable definitions in
<defs>to simplify your code; - Use clear and meaningful
ids for the elements defined; - Combine
<defs>with CSS attributes or transformations to efficiently reuse graphical resources.
For advanced usage, combine <defs> with other tags like <use> to create reusable groups.
Â
Browser compatibility
The <defs> tag is supported by all modern browsers:
| Browser | Compatibility |
|---|---|
| Chrome | Yes |
| Firefox | Yes |
| Safari | Yes |
| Edge | Yes |
| Internet Explorer | Partial (IE 9+) |