SVG Grouping Elements

The g element (short for "group") is SVG's main organizational tool. It lets you treat multiple elements as a single unit, which makes your code cleaner and more powerful.

What Can You Do with a Group?

Wrapping elements in a g element does two main things:

  1. Share styles: Any presentation attributes placed on the g element (like fill, stroke, or opacity) are inherited by all child elements. You only need to write the style once.
  2. Apply transformations together: A transform attribute on a g element moves, rotates, or scales all children at once as if they were a single object.

Example: Shared Styles on a Group

Rather than setting fill, stroke, and opacity individually on each of the three shapes below, they are all set once on the containing g element:

View Output

Individual Overrides

Inherited group styles can always be overridden on a per-element basis. If you add a fill="tomato" directly to one of the child elements inside the group, it takes precedence over the group's fill for that specific element. The group style acts as a default.

Groups and Accessibility

The g element also accepts a title child element that can provide an accessible label for the group, helping screen readers understand the purpose of a set of shapes. This is especially useful for SVG diagrams and icons:

<g role="img" aria-labelledby="iconTitle">
  <title id="iconTitle">A friendly face</title>
  ...shapes...
</g>