How to Group SVG Shapes Using the G Element
Grouping multiple geometric shapes in Scalable Vector Graphics (SVG)
is achieved using the <g> container element. This
article covers how the <g> element works, how to
combine various vector shapes into unified components, and how to apply
collective styling, transformations, and identifiers to make complex SVG
graphics more manageable and reusable.
The Purpose of the SVG
<g> Element
The SVG <g> element acts as a non-rendering
container used to logically group related graphical elements together.
When shapes such as <rect>,
<circle>, <line>, or
<path> are nested within a <g>
tag, they can be treated as a single composite object. This eliminates
redundant code, enhances structural organization, and allows for
collective manipulation through CSS and JavaScript.
Basic Syntax and Grouping Shapes
To group multiple shapes, nest the child shape elements directly
inside an opening <g> and closing
</g> tag.
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<g id="car-wheel">
<circle cx="100" cy="100" r="50" fill="#333333" />
<circle cx="100" cy="100" r="25" fill="#cccccc" />
<circle cx="100" cy="100" r="5" fill="#111111" />
</g>
</svg>In this example, three separate circles are grouped into a single unit representing a wheel.
Inheriting Shared Attributes and Styles
Any presentation attribute applied to the <g>
element is automatically inherited by its descendant elements, unless
explicitly overridden on a child element. This significantly reduces
code repetition.
<g fill="#4A90E2" stroke="#1D3557" stroke-width="2" opacity="0.85">
<rect x="20" y="20" width="60" height="60" />
<circle cx="130" cy="50" r="30" />
<polygon points="180,80 210,20 240,80" />
</g>All three shapes inside this group automatically inherit the blue fill, dark stroke, stroke width, and opacity defined at the group level.
Applying Collective Transformations
Transformations applied to a group affect all child elements
simultaneously relative to the group’s coordinate space. This makes
moving, scaling, or rotating a composite object straightforward using
the transform attribute.
<g transform="translate(50, 50) rotate(45 100 100) scale(1.2)">
<rect x="75" y="75" width="50" height="50" fill="orange" />
<circle cx="100" cy="100" r="20" fill="purple" />
</g>Applying transform to the parent group prevents the need
to calculate new coordinates for each individual shape.
Reusability and Organization
The <g> element is essential for modular design
workflows:
- Identification: Adding
idorclassattributes enables precise targeting for CSS styling and DOM event listeners. - Component Reuse: Groups assigned an
idcan be referenced and duplicated throughout an SVG document using the<use>element (e.g.,<use href="#car-wheel" x="120" />). - Nested Hierarchy:
<g>elements can be nested inside other<g>elements to build complex, multi-layered visual hierarchies.