Reputation: 563
I'm trying to translate my svg text (axis label) in order I can center it with svg container. I've tried with this code:
svg.append("text")
.attr("x", 100)
.attr("y",100)
.attr("transform", "translate(-50%, -50%)")
.text("any text");
Moreover nothing happens. Other svg elements are translated with no problems, but, The text doesn't move from its original position. What is wrong, whats is the correct way to translate svg text?
Upvotes: 2
Views: 2990
Reputation: 15912
D3 Version 6 - Working Example with element
const fontSize = 1.714em;
innerCircleText.append('text')
.attr('text-anchor', 'middle')
.style('font-size', `${fontSize}em`)
.style('transform', `translate(0, ${0.5 / fontSize}em)`)
.text('24')
This was used to slightly move the text closer to center as the size of the font moved around a bit from middle.
Note: If I leave off the "em" in this
.style('transform', translate(0, ${0.5 / fontSize}em)
)
The browser will not use it. Yet if I leave it on, and 0 has no metric, this is what shows up in browser... transform: translate(0px, 0.291715em)
with the transform working...
Upvotes: 0
Reputation: 3001
Remove the %
signs from the arguments you pass to translate
:
svg.append("text")
.attr("x", 100)
.attr("y", 100)
.attr("transform", "translate(-50, -50)")
.text("any text");
You can check the MDN docs.
Upvotes: 1