SVG: Structure Elements

By Xah Lee. Date: . Last updated: .

“g” element

The “g” element is used to group several graphics elements together.

<g id="…" style="…" >…</g> → group a set of elements.

Grouping is useful because:

<svg width="100" height="100">
<g id="abc46"
 style="fill:yellow; stroke:blue; stroke-width:5" >
 <rect x="9" y="0" width="30" height="80"/>
 <circle cx="50" cy="50" r="20"/>
</g>
</svg>
example of using g to group.

To use the grouped graphics in other places, use the use element.

Document Structure – SVG 1.1 (Second Edition)#Groups

“use” Element

The use element lets you re-use graphics elements without needing to define them again.

The basic syntax of “use” is this:

<use xlink:href="#id" x="x-coord" y="x-coord" />

The elements that can be used by use are: { g, symbol, svg, use }

The use element has optional attributes x, y, width and height which are used to map the graphical contents of the referenced element onto a rectangular region within the current coordinate system.

<svg width="100" height="100">
<g id="abc46"
 style="fill:yellow; stroke:blue; stroke-width:5" >
 <rect x="9" y="0" width="30" height="80"/>
 <circle cx="50" cy="50" r="20"/>
</g>

<use xlink:href="#abc46" x="50" y="0" />

</svg>
example of use

Document Structure – SVG 1.1 (Second Edition)#UseElement

“defs” Element

The defs element lets you define some graphics element, then re-use the definition elsewhere. (it's like a variable in programing language, where the variable name is the id attribute value.)

The basic syntax for defs element is:

<defs id="id">graphics_elements</def> → define several things, to be referenced by id.

<svg width="100" height="100">
<defs id="c">
 <circle cx="10" cy="10" r="10"/>
</defs>
</svg>
Example of defs

Note: “defs” does not render the graphics. It only defines the graphics.

To use defined elements, use use tag.

Document Structure – SVG 1.1 (Second Edition)#Head

“symbol” Element

Document Structure – SVG 1.1 (Second Edition)#SymbolElement

“image” Element

Document Structure – SVG 1.1 (Second Edition)#ImageElement

SVG tutorial

  1. SVG Basics
  2. Path
  3. Path Elliptical Arc
  4. Circle Arc
  5. Specifying Styles
  6. Shape Styles
  7. Viewport
  8. viewBox
  9. ViewBox Unit Size
  10. Coordinate Transformation
  11. Text Element
  12. Font Size
  13. Structure Elements
  14. Scripting SVG
  15. SVG Clock
  16. Animation

Canvas Intro

  1. Canvas vs SVG
  2. Canvas intro
  3. Demo: Halma
  4. Demo: Raycaster
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials