Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering an SVG element Chrome vs Safari

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:

Chrome vs Safari

I created a jsFiddle with this test case:

https://jsfiddle.net/yq11jot0/

How do I vertically center the text inside the square?

like image 726
RemiX Avatar asked Oct 20 '25 07:10

RemiX


1 Answers

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>
like image 140
RemiX Avatar answered Oct 22 '25 22:10

RemiX