SVG Positioning
I'm having a play with SVG and am having a few problems with positioning. I have a series of shapes which are contained in the g
group tag. I was hoping to use it like a container, so I could set its x position and then all the elements in that group would also move. But that doesn't seem to be possible.
- How do most people go about positioning a group of elements which you wish to move in tandem?
- Is there any concept of relative positioning? e.g. relative to its parent
Solution 1:
Everything in the g element is positioned relative to the current transform matrix.
To move the content, just put the transformation in the g element:
<g transform="translate(20,2.5) rotate(10)">
<rect x="0" y="0" width="60" height="10"/>
</g>
Links: Example from the SVG 1.1 spec
Solution 2:
There is a shorter alternative to the previous answer. SVG Elements can also be grouped by nesting svg elements:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<svg x="10">
<rect x="10" y="10" height="100" width="100" style="stroke:#ff0000;fill: #0000ff"/>
</svg>
<svg x="200">
<rect x="10" y="10" height="100" width="100" style="stroke:#009900;fill: #00cc00"/>
</svg>
</svg>
The two rectangles are identical (apart from the colors), but the parent svg elements have different x values.
See http://tutorials.jenkov.com/svg/svg-element.html.
Solution 3:
As mentioned in the other comment, the transform
attribute on the g
element is what you want. Use transform="translate(x,y)"
to move the g
around and things within the g
will move in relation to the g
.