apike.ca

Grouping in SVG (g tag)

By mbystedt on Feb 27, 2014, 5:34:10 PM

The grouping of tags using the 'g' element is the primary way SVG documents are structured. Elements outside and inside of a group are treated identically and there is no limit to the depth of grouping. Grouping allows you to style using inheritance, refer to it using JavaScript and make copies using the use tag.

<g>
Attribute
Explanation
Example
id
The unique name of the group. This is used to reference the group.
fill
The default fill color for the group
opacity
The default opacity for the group.
etc.
See below
Presentation Attributes

Inherited Attributes

One major benefit of grouping is the g tag can have presentation attributes that are inherited. The next example only shows a couple presentation attributes. In fact, any attribute can be applied to the group even if some of the elements inside the group do not use it.

<g id="group1" fill="green" opacity="0.9" >
  <rect x="20" y="20" width="100" height="100" opacity="0.5" />
  <rect x="80" y="80" width="100" height="100" fill="gray" />
</g>
Code 1. The g tag

An attribute set in an enclosing group is only used if the same attribute on the member is set to "inherit". Most attributes are set to inherit by default.

xyz-attribute="inherit"

See also: Styling SVG Documents

Composition Attributes

Not all attributes can be inherited. Opacity and other composition attributes (like masks, clipping planes and transformations) are applied to the group as a whole after the individual elements have been rendered. An opacity of 0.9 makes the entire group 0.1 more transparent when it is drawn. It does not change the opacity of elements of the group.

The Use of Grouped Elements

The next sections example shows how grouping fits into the other two organization tools in SVG: the 'defs' element and the 'use' element.