如何在SVG中居文本?

And*_*rew 7 html svg

我需要在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>
Run Code Online (Sandbox Code Playgroud)

Pau*_*eau 6

文本相对于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>
Run Code Online (Sandbox Code Playgroud)