Assume the following svg document:
<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <text x="20" y="20">My text</text> </svg>
Now what i want to do is reposition this text using css.
I have tried adding style="dx:20"
and style="transform: translate(20)"
. Both have no effect in firefox and safari. Adding these as normal attributes works fine but then i can't split the positioning from the actual code. Setting x
, y
, left
and top
in the style isn't working either.
Is there a way to position an svg element using css?
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 .
Not only does it mean that SVG properties can be styled using CSS as presentation attributes or in style sheets, but this also can be applied to CSS pseudo-classes such as :hover or :active . SVG 2 also introduces more presentation attributes that can be used as styling properties.
SVG elements doesn't support the standard xpath format. It has a different format. 2. Shadow DOM elements don't support xpath so we can write only cssSelector for shadow DOM elements.
You can use a nested SVG to group elements together and then position them inside the parent SVG. Now, you can also group elements together and position them using the <g> group—by wrapping elements inside a group <g> element, you can position them on the canvas by using the transform attribute.
I've managed to move some SVG text in chrome using the following CSS:
text.identity{ transform: translate(74px,0px); -ms-transform: translate(74px,0px); /* IE 9 */ -webkit-transform: translate(74px,0px); /* Safari and Chrome */ -o-transform: translate(74px,0px); /* Opera */ -moz-transform: translate(74px,0px); /* Firefox */ }
However, it's not budging in Firefox...
I came here looking for a fix but fixed the issue myself, thought I would share:
transform: translate(100px, 100px)
Appears to work in all modern browsers except for Internet Explorer, right up until Microsoft Edge (which isn't even out yet) which is quite disappointing. The elements I've tested on are:
<path> <polygon> <g>
The only issue I've had is with <text>
elements, and the solution there is to wrap the <text>
in a <g>
and apply the transformation to that. That should also work for any elements I haven't yet tested that have issues with transform: translate()
.
I haven't found a decent fallback for Internet Explorer, instead I've made sure that the transforms aren't vital to the function of the SVG.
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