SVG Concepts - Grouping in SVG

Print this Page             Close Window

Grouping in SVG

An SVG document can have a hierarchical structure which contains a nested collection of grouping and graphics elements.

Grouping in SVG is achieved by the <g> element, which is a container element for grouping and naming collection of related graphics elements.

The <g> element has three major uses:

  • To group a set of drawing elements share the same attribute
  • To define a new coordinate system for a set of elements by applying a transformation to each coordinate specified in this set of elements
  • To be used as the source or destination of a reference

Here is the basic syntax for using the <g> element in a document:

 .......
 <g style="fill:red;stroke:black">
   <circle cx="70" cy="100" r="50" />
   <rect x="150" y="50" width="100" height="100" />
 </g>
</svg>

The <g> element can have any of the attributes or style properties defined for it that are generally applicable to individual drawing elements. In the example above, both the circle and rectangle will be rendered with the interior red and the border black.

A group of elements, as well as individual objects, can be given a name using the id attribute. Named groups are needed for several purposes such as animation and re-usable objects. For example,

 .......
 <g id="red_group" style="fill:red;stroke:black">
  <circle cx="70" cy="100" r="50" />
  <rect x="150" y="50" width="100" height="100" />
 </g>
</svg>

The grouping constructs can be used in conjunction with the <desc> and <title> elements to provide description and semantics about the group.

 .......
 <g>
   <title>Company sales by region</title>
   <desc> This is a bar chart which shows company sales by region.</desc>
          <!-- Bar chart defined as vector data -->
  </g>
</svg>

The <g> element can contain other <g> elements nested within it, to an arbitrary depth. Thus, the following is valid SVG:

  <g>
       <g>
             <g>
                   <g>
                   </g>
             </g>
       </g>
  <g>

A locally defined attribute can override the common attribute defined insides the <g> element.

Any Drawing element that is not contained in a <g> element can be considered as a group of its own.