<g>
The <g>
tag is used to group multiple elements in an SVG graphic.
It allows you to structure and manipulate a set of SVG elements easily by treating them as a single group. This includes transformations (such as rotation or displacement) or the application of shared attributes (such as color).
By grouping elements, you can simplify management and reduce repetitions in your code. 😊
Structure and syntax of the <g>
tag
Structure
The <g>
tag is always used within an <svg>
tag.
Here is a simple example of syntax:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(50,50)" fill="blue">
<rect width="50" height="50" />
<circle cx="75" cy="75" r="25" />
</g>
</svg>
In this example:
- The group
<g>
contains a rectangle and a circle; - The group is displaced by 50 pixels on the x and y axes thanks to
transform="translate(50,50)"
; - The blue color is applied to all elements of the group thanks to the
fill
attribute.
Here is the result of this example:
Note that using the
<g>
tag does not change the visual appearance of the grouped elements, but simplifies their management.
Example
Here is an example grouping multiple circles with applied transformations to the group:
<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<g transform="rotate(45, 150, 100)" fill="none" stroke="black" stroke-width="2">
<circle cx="150" cy="100" r="40" />
<circle cx="200" cy="100" r="40" />
<circle cx="100" cy="100" r="40" />
</g>
</svg>
In this example:
- The group
<g>
is rotated by 45° around the point (150, 100) thanks totransform="rotate(45, 150, 100)"
. - The circles share the same border styles (
stroke
,stroke-width
, andfill
).
Here is the result:
Attributes
Here are the main attributes for the <g>
tag:
transform
: applies transformations (such astranslate
,rotate
, orscale
) to the group;fill
: modifies the fill color for all child elements (inheritable attribute);stroke
: specifies the border color for all child elements (inheritable attribute);stroke-width
: provides the widths of the borders for all child elements.
Best practices
Here are some tips for using this tag effectively:
- Group elements together to simplify management and reutilization;
- Use transformations (such as
translate
orrotate
) directly on the group instead of each individual element; - Apply common styles on the group with global attributes like
fill
orstroke
.
For a more complex hierarchy, combine the
<g>
tag with other tags like<defs>
to create reusable groups.
Browser compatibility
The <g>
tag is compatible with all modern browsers:
Browser | Compatibility |
---|---|
Chrome | Yes |
Firefox | Yes |
Safari | Yes |
Edge | Yes |
Internet Explorer | Partial (IE 9+) |