SVG: Text centerd differently in FF and Chrome

2019-08-30 01:08发布

问题:

I have the following SVG content

<svg height="64" width="64" class="ng-star-inserted">
  <rect rx="10" ry="10" style="fill:silver;stroke:black;stroke-width:5;opacity:0.5" x="0" y="0" height="64" width="64">
  </rect>
  <text alignment-baseline="middle" text-anchor="middle" x="50%" y="50%">
 missing 
  </text>
</svg>

which makes essentially a grey box with some text. The text should be centered - vertically and horizontally. I place the whole thing in a Bootstrap 4 structure next to a input field (type file). But somehow the center of the text in the SVG seems to be calculated differently depending on the browser.

The whole code looks like:

<li class="media">
  <div class="mr-3">
    <svg height="64" width="64" class="ng-star-inserted">
      <rect rx="10" ry="10" style="fill:silver;stroke:black;stroke-width:5;opacity:0.5" x="0" y="0" height="64" width="64">
      </rect>
      <text alignment-baseline="middle" text-anchor="middle" x="50%" y="50%">
     missing 
      </text>
    </svg>
  </div>
  <div class="media-body">
    <h5 class="mt-0 mb-1">{{getLabel()}}</h5>
    <input class="form-control-file" type="file" type="file" >
  </div>
</li>

as seen in the picture the text missing is on the left side (FF) just above the supposed center. I can change the center alignment of 50% to 32px which would be perfect for Chrome but for FF it should be 34px. I guess FF starts calculating for the x the whole row height and and not image-start.

Changing alignment-baseline="middle" to center, hanging baseline did not fix the problem either.

Is there a way to fix it so it works in both browser identically?

回答1:

Add dominant-baseline="middle" and edit your code like this:

 <text alignment-baseline="middle" dominant-baseline="middle" text- 
    anchor="middle" x="50%" y="50%">
     missing 
 </text>

Link to documenttion

Here's the codepen snippet that I tested in both Chrome and Firefox.