SVG defs Elements

Jakob Jenkov
Last update: 2014-06-15

The SVG <defs> element is used to embed definitions that can be reused inside an SVG image. For instance, you can group SVG shapes together and reuse them as a single shape.

A defs Example

Here is a simple <defs> element example:

<svg>
    <defs>
        <g>
            <rect x="100" y="100" width="100" height="100" />
            <circle cx="100" cy="100" r="100" />
        </g>
    </defs>
</svg>

Shapes defined inside a <defs> element are not displayed in the SVG image. They have to be referenced by a <use> element before they are shown. Here is an example:

<svg>
  <defs>
    <g id="shape">
        <rect x="50" y="50" width="50" height="50" />
        <circle cx="50" cy="50" r="50" />
    </g>
  </defs>

  <use xlink:href="#shape" x="50" y="50" />
  <use xlink:href="#shape" x="200" y="50" />

</svg>

Before the <g> element can be referenced, it must have an ID set on it via its id attribute. The <use> element references the <g> element via its xlink:href attribute. Notice the # in front of the ID in the attribute value.

The <use> element specifies where to show the reused shapes via its x and y attributes. Notice that the shapes inside the <g> element are located at 0,0. That is done because their position is added to the position specified in the <use> element.

Here is the resulting image:

The blue dots are not part of the example. They are added to show the x and y of the two <use> elements.

What Elements Can Be Defined Inside the defs Element?

You can put the following elements inside the <defs> element:

  • Any shape element (rect, line etc.)
  • g
  • symbol

Jakob Jenkov

Featured Videos




















Advertisements

High-Performance
Java Persistence
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next