Groups - the <g>
tag in SVG - are somewhat akin to <div>
elements on web pages, in that they contain and control related SVG elements. However, there are some very distinct differences between <g>
and <div>
elements are important to understand:
- Just like
<div>
elements,<g>
elements allow their children to inherit presentational styles:<svg viewBox="0 0 400 160"> <g fill="#33E" stroke="#000" stroke-width="10px"> <circle cx="88" cy="80" r="62"/> <rect x="246" y="17" width="123" height="123"/> </g> </svg>
Which produces:
- Similarly, transforms on groups are inherited by the elements inside them.
- However, unlike
<div>
elements, SVG groups cannot be positioned. They can be translated into new locations via atransform
, but because they do not havex
ory
attributes, they cannot be positioned in the SVG document*. - Again like
<div>
elements,<g>
elements can take an id attribute (and less commonly, classes), for further styling or scripting:<svg viewBox="0 0 400 163"> <style type="text/css"> #svg-container { fill: hsl(45,80%,80%); stroke: rgba(0,0,0,0.3); stroke-width: 10px; } </style> <g id="svg-container"> <circle cx="88" cy="80" r="62"/> <rect x="246" y="17" width="123" height="123"/> </g> </svg>
Which creates:
(And just like CSS inheritance, presentational rules applied directly to elements will overwrite any rules from their parent if the two conflict)
- Finally, unlike
<div>
elements,<g>
elements can have the own nested<title>
and<desc>
elements for further information and accessibility.
* You can get around this by nesting <svg>
elements inside groups, since SVG elements do have x
and y
attributes. I’ll explore this advanced topic later.
Photograph by Dina Belenko, used with permission
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.