First, let's see what is a group and what is a symbol.
<g>
is a container used to group other SVG elements.<symbol>
is used to define graphical template objects.Then, let's find out what they have in common.
<use>
.And that's about all there is, as to their function. Neither of these elements draws something by itself.
So, what is the difference and when to prefer one over another?
The contents of a <symbol>
are not directly renderered
The contents of a <g>
are directly rendered unless the <g>
is itself not rendered. E.g. if the <g>
were in a symbol.
So if you wrote something like
<svg>
<g id="g">
<rect id="g-rect" .../>
</g>
<symbol id="s">
<rect id="symbol-rect" .../>
</symbol>
<use href="#g" transform="translate(100,100)" />
<use href="#s"/>
</svg>
We'd see 3 rect elements rendered, the g-rect would display twice, once via the <g>
element and again via the <use>
reference. The symbol-rect would only display once i.e. via the <use>
element.
A symbol element also supports viewBox and preserveAspectRatio properties, a g element does not.
The SVG specification does document this...
The key distinctions between a ‘symbol’ and a ‘g’ are:
- A ‘symbol’ element itself is not rendered. Only instances of a ‘symbol’ element (i.e., a reference to a ‘symbol’ by a ‘use’ element) are rendered.
- A ‘symbol’ element has attributes ‘viewBox’ and ‘preserveAspectRatio’ which allow a ‘symbol’ to scale-to-fit within a rectangular viewport defined by the referencing ‘use’ element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With