如何在SVG中居中文本?

8

我需要在SVG对象内水平居中文本,而无需定义x坐标。我正在尝试寻找CSS中text-align: center的替代方法。我已经使用了text-anchor: middle,但它不起作用。以下是我的代码:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
 <stop offset="0" stop-color="#FFE89C" stop-opacity="1"/>
 <stop offset="0.2" stop-color="#FFE192" stop-opacity="1"/>
 <stop offset="0.4" stop-color="#ffd47a" stop-opacity="1"/>
 <stop offset="0.6" stop-color="#ffc967" stop-opacity="1"/>
 <stop offset="0.8" stop-color="#febd52" stop-opacity="1"/>
 <stop offset="1" stop-color="#fdba4c" stop-opacity="1"/>
</linearGradient>
</defs>
<text fill="url(#grad1)" x="73" y="50">50</text>
</svg>

text-anchor: middle 是正确的方法。实际上没有其他方法可以做到。你说的“它不起作用”是什么意思? - Paul LeBeau
文本相对于x轴居中,我希望它相对于父级SVG容器居中,否则如果文本内容的长度发生变化,就必须更改x坐标。看起来没有其他方法可以做到这一点。谢谢。 - Andrew
3个回答

14

文本相对于x轴居中,我希望它相对于父级SVG容器居中,否则如果文本内容的长度发生变化,就需要改变x坐标。

你只需要将文本定位在viewBox中心位置,然后使用text-anchor="middle",文本就会保持居中。

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 150 60">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop offset="0" stop-color="#FFE89C" stop-opacity="1"/>
      <stop offset="0.2" stop-color="#FFE192" stop-opacity="1"/>
      <stop offset="0.4" stop-color="#ffd47a" stop-opacity="1"/>
      <stop offset="0.6" stop-color="#ffc967" stop-opacity="1"/>
      <stop offset="0.8" stop-color="#febd52" stop-opacity="1"/>
      <stop offset="1" stop-color="#fdba4c" stop-opacity="1"/>
    </linearGradient>
  </defs>

  <text fill="url(#grad1)" x="75" y="50" text-anchor="middle"font-size="40">50</text>
</svg>


谢谢,保罗,现在我明白了。 - Andrew

0

text-anchor="middle" 通过使用svg元素的这个属性,您可以使您的svg元素的文本对齐。


0

CSS中使非文本对象居中

我尚未在SVG块内测试过这个方法,但这是CSS中让大多数任何东西在div中居中的方法。我在需要居中的项目中使用它,而text-align不适用。

简而言之:使用自动宽度、左右对齐,并给它一个总宽度参数。

// Classes
.center-block {
  margin-left: auto;
  margin-right: auto;
  width: 40%;  // Use whatever percentage of the container width you need
}

所有3个参数都是必需的,否则它不会居中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接