No, this is not a hip hop song about SVGs, sorry to those of you who were expecting that. This is another post about good ol’ SVG graphics. So most of us know that there is a lot that you can do with SVGs and it can all be done in many different ways. The SVG defs element can be used to make SVG code simpler, cleaner, and better.

What Exactly is the Defs Element?

The SVG defs element is a used to contain items that can be referenced and reused from within the current SVG document.

Items contained within the defs element are not actually rendered because they are not part of the “rendering tree” but they are part of the “source tree” so they they are available and are able to be referenced elsewhere.

For performance reasons it is recommended that the defs element come before all other elements. Since it contains items that are referenced from other locations within the document it works better when they are created before they are referenced.

It is also recommended to use the defs element whenever possible because it’s easier to understand from a readability perspective and it’s also better for accessibility.

How is it Used?

Let’s say you have a design that makes use of multiple circles. You can just add one circle item in the defs element and then call it using the SVG use element like so:

One way that you could use this is if you were to save all of the icons for your website or application into a single SVG. You could then grab all of the reusable elements and toss them into your defs element and then just call them setting them up with CSS for those icons that use them. This could greatly simplify and reduce your overall code within the SVG file itself.

A Real World Example

See the Pen SVG Defs and Use by Brian (@brianmtreese) on CodePen.

Browser Support

ie9 and aboveChrome 17 and aboveFire Fox 17 and aboveOpera 15 and aboveSafari 6 and above

The SVG defs element has good browser support working in all modern browsers. Not supported in Internet Explorer 8 and below.