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
As mentioned in the other comment, the
transform
attribute on theg
element is what you want. Usetransform="translate(x,y)"
to move theg
around and things within theg
will move in relation to theg
.There are two ways to group multiple SVG shapes and position the group:
The first to use
<g>
withtransform
attribute as Aaron wrote. But you can't just use ax
attribute on the<g>
element.The other way is to use nested
<svg>
element.In this way, the #group1 svg is nested in #parent, and the
x=10
is relative to the parent svg. However, you can't usetransform
attribute on<svg>
element, which is quite the contrary of<g>
element.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:
Links: Example from the SVG 1.1 spec
There is a shorter alternative to the previous answer. SVG Elements can also be grouped by nesting svg elements:
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.