<defs>

2 min read
Believemy logo

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.
Good to know

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:

HTML
<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 an id (#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:

HTML
<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:

Warning

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.
Good to know

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:

BrowserCompatibility
ChromeYes
FirefoxYes
SafariYes
EdgeYes
Internet ExplorerPartial (IE 9+)

Related terms

Discover our hTML and CSS glossary

Browse the terms and definitions most commonly used in HTML and CSS development.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.