I'm trying to center an SVG element in a parent element. However, I'm finding discrepancies between Chrome and Safari. The following code centers the text nicely inside the square on Chrome, but not on Safari:
<svg width="200px" height="200px">
<g transform="translate(70,70)">
<path d="M -40,-40 l 80,0 l 0,80 l -80,0 l 0,-80 z" style="fill: gray"></path>
<g>
<text text-anchor="middle" dominant-baseline="middle" style="fill: white" transform="scale(2)">
<tspan>test</tspan>
</text>
</g>
</g>
</svg>
Result:

I created a jsFiddle with this test case:
https://jsfiddle.net/yq11jot0/
How do I vertically center the text inside the square?
Apparently, Safari wants the inner tspan have the dominant baseline set to middle. So this also works on Safari:
<svg width="500" height="500" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(50,50)">
<path class="node" d="M -40,-40 l 80,0 l 0,80 l -80,0 l 0,-80" style="fill: rgb(247, 61, 0);"></path>
<g>
<text text-anchor="middle" fill="white"><tspan dominant-baseline="middle">test</tspan></text>
</g>
</g>
</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