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?
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:
<svg height="130px" width="250px"> <defs> <circle id="circle" cx="50" cy="50" r="50" /> </defs> <use xlink:href="#circle" x="10" y="20" fill="#00deb7" /> <use xlink:href="#circle" x="130" y="20" fill="#ff495d" /> </svg>
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
The SVG defs element has good browser support working in all modern browsers. Not supported in Internet Explorer 8 and below.