【问题标题】:What is the relationship between font-size and x/y percentages for positioning text elements in an SVG?在 SVG 中定位文本元素的字体大小和 x/y 百分比之间有什么关系?
【发布时间】:2021-10-09 19:46:26
【问题描述】:

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

在下面的示例中,每个正方形的高度和宽度为 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>
 

【问题讨论】:

  • @RobertLongson 嗯,显然是这样。也适用于所有不同类型的字体大小。

标签: svg


【解决方案1】:

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

<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>

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2013-10-07
    • 2021-05-15
    • 2014-09-15
    • 2011-04-25
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多