Reputation: 1639
I know that there are two ways in SVG to group shapes together and position them as a collection: nesting <svg>
tag and <g>
grouping. However, I don't see much difference between them. For example, the following two pieces of code produce exactly the same result:
Using group (jsfiddle): https://jsfiddle.net/8q4on01m/5/
<svg width="5000" height="5000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g transform="translate(200 200)">
<rect x="0" y="0" height="100" width="100" style="fill: yellow"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: green" transform="rotate(45) translate(200 100)"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: red" transform="translate(200 100)"></rect>
</g>
</svg>
Using <svg>
(jsfiddle):
<svg width="5000" height="5000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="200" y="200">
<rect x="0" y="0" height="100" width="100" style="fill: yellow"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: green" transform="rotate(45) translate(200 100)"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: red" transform="translate(200 100)"></rect>
</svg>
</svg>
Which one is preferred/recommended? What are the pros and cons, important features of each? I am especially interested in handling bubbling click events issues.
Upvotes: 20
Views: 13699
Reputation: 101830
In your two examples, there is no real difference between <svg>
and <g>
.
However <svg>
can do many things that <g>
cannot. Groups are just a passive grouping of elements, and all they can really do is specify some properties that their children all inherit.
Inner <svg>
elements establish a new viewport. So you can do everything that the outermost <svg>
can (actually more).
For example, by adding width
, height
and viewBox
attributes to the inner SVG, you can scale its contents.
<svg width="5000" height="5000" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="200" y="200" width="100" height="100" viewBox="0 0 300 300">
<rect x="0" y="0" height="100" width="100" style="fill: yellow"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: green" transform="rotate(45) translate(200 100)"></rect>
<rect x="0" y="0" height="100" width="100" style="fill: red" transform="translate(200 100)"></rect>
</svg>
</svg>
This is not a very exiting example. Instead, have a look at this one from the SVG specification.
Upvotes: 17