apike.ca

Defining in SVG (defs tag)

By mbystedt on Feb 21, 2014, 1:57:20 AM

The defs element is used to define SVG elements without rendering them. Combined with a 'g' tag, it can be used to create a template for a intricate graphic that contains many elements. In general, even things that do not display like gradients and patterns in SVG must be predeclared. It makes sense to bundle everything into a definition section at the top of your SVG document.

All elements in a defs tag that will be referenced should have an unique id attribute. It's not necessary to give everything an id.

<defs>
  <radialGradient id="myRadGrad" r="90%" spreadMethod="reflect">
    <stop offset="0" stop-color="#eee" />
    <stop offset="10%" stop-color="#ccc" />
    <stop offset="60%" stop-color="#555" />
    <stop offset="80%" stop-color="#000" />
  </radialGradient>
 
  <rect id="myRect" x="0" y="0" width="100" height="100" fill="blue" />
</defs>
Code 1. Defining a radial gradient and rectangle inside a defs tag. All graphical elements in the defs tag are hidden.

Where a 'g' element can be used, a 'defs' element can also be used and vis versa. The results and uses of each tag are quite different. Nesting 'defs' in particular is valid but makes no sense and has no effect. It's still not going to be rendered!

The 'defs' element has no (interesting) attributes in case you're wondering. It's recommended to keep all definitions in a single defs tag at the top of each SVG document fragment and only make reference to elements by id to ones in the 'defs' tag. This way you'll always know where to look for definitions.