如何将文本居中在SVG g元素内?

6

我尝试了这个http://jsfiddle.net/helderdarocha/e4bAh/,但它只能水平居中。这是代码和JSFiddle链接:

  <svg width="400" height="400">
    <g class="point" transform="translate(225,217)">
      <circle></circle>
      <text class="pointIndex" y="50">
        <tspan text-anchor="middle">10</tspan>
      </text>
    </g>
  </svg>

 <style>
    .point circle {
      cursor: pointer;
      text-align: center;
      fill: #E2137E;
      r: 10;
      stroke: #333;
      stroke-width: 2px;
    }
 </style>

如何将.pointIndex居中在.point内? https://jsfiddle.net/alexcheninfo/9a112b63/6/
1个回答

6

最终问题出在text.pointIndex中的y="50",将其改为y="5"即可使其垂直居中。

JS Fiddle - 已更新

.point circle {
  cursor: pointer;
  text-align: center;
  fill: #E2137E;
  r: 10;
  stroke: #333;
  stroke-width: 2px;
}
<svg width="400" height="400">
  <g class="point" transform="translate(225,217)">
    <circle></circle>
    <text class="pointIndex" y="5">
      <tspan text-anchor="middle">10</tspan>
    </text>
  </g>
</svg>


它需要向上移动几乎圆的高度,即 **50px**,但如果你使用 **50px**,文本的顶部将出现在圆的相同顶点,因此只需稍微向下移动一点以使其居中。 - Mi-Creativity
我看到了,但很奇怪,圆的半径是10px,描边为2px。那么圆不应该高44px吗? - alexchenco
不是圆形的问题,是文本中的 y=50,应该改为 y="5",不需要使用CSS。我的错。https://jsfiddle.net/Mi_Creativity/9a112b63/8/ - Mi-Creativity
这是程序相关内容的翻译,从英语到中文。只返回翻译后的文本:https://jsfiddle.net/seahorsepip/9a112b63/9/。在这里,我把圆圈变大了,以展示基线属性的魔力:P - seahorsepip
很好,我很少使用SVG,所以不知道很多属性,但是有了这个属性,更容易和更合适,因为你不需要自己进行计算,把它作为答案发布吧,伙计。 - Mi-Creativity
显示剩余8条评论

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