在 SVG 中定位文本元素的字体大小和 x/y 百分比之间有什么关系?

What is the relationship between font-size and x/y percentages for positioning text elements in an SVG?

我正在尝试根据某些形状使文本居中。

在下面的示例中,每个正方形的高度和宽度均为 SVG 的 50%。我试图将非常大的“X”字符居中。直觉上,我想将文本的 x 和 y 设置为任何正方形的中心(25%、25% 或 25%、75% 或 75%、75% 或 75%、25%),但它已关闭。我需要稍微调整百分比以使它们居中。

在下面的示例中,看起来我的直觉在左上角是错误的,而调整 y% 使其在右上角稍微居中。包含较小的蓝色和绿色方块以准确显示 25%、25% 和 25%、75% 的位置。

我注意到当字体大小改变时这也会改变。有没有办法使用百分比根据字体大小使文本居中?我缺少什么关键概念来理解为什么这不起作用?

<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 200 200">
  <style>
.f{font-family:monospace;font-size:80pt}
  </style>
  <rect width="50%" height="50%" y="0%" fill="red"/>
  <rect width="50%" height="50%" y="50%" fill="green"/>
  <rect width="50%" height="50%" y="0%" x="50%" fill="yellow"/>
  <rect width="50%" height="50%" y="50%" x="50%" fill="blue"/>
  
  <text x="25%" y="25%" class="f" dominant-baseline="middle" text-anchor="middle">X</text>
  <text x="75%" y="29%" class="f" dominant-baseline="middle" text-anchor="middle" fill="blue">X</text>
  <rect width="25%" height="25%" y="25%" x="25%" fill="blue"/>
  <rect width="25%" height="25%" y="25%" x="75%" fill="green"/>
</svg>
 

字体允许显示所有字符。

您需要更改基线

看起来你想要 dominant-baseline="central" 而不是 middle。

<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 200 200">
  <style>
.f{font-family:monospace;font-size:80pt}
  </style>
  <rect width="50%" height="50%" y="0%" fill="red"/>
  <rect width="50%" height="50%" y="50%" fill="green"/>
  <rect width="50%" height="50%" y="0%" x="50%" fill="yellow"/>
  <rect width="50%" height="50%" y="50%" x="50%" fill="blue"/>
  
  <text x="25%" y="25%" class="f" dominant-baseline="central" text-anchor="middle">X</text>
  <text x="75%" y="29%" class="f" dominant-baseline="central" text-anchor="middle" fill="blue">X</text>
  <rect width="25%" height="25%" y="25%" x="25%" fill="blue"/>
  <rect width="25%" height="25%" y="25%" x="75%" fill="green"/>
</svg>