【问题标题】:How can I center the text element inside <g> element? [duplicate]如何在 <g> 元素中居中文本元素? [复制]
【发布时间】:2021-10-23 10:30:53
【问题描述】:

这是我的 SVG 的结构

<g id="CDT-B6-2">
   <path id="CDT-B6-box"/>
   <text x="1210" y="993" id="CDT-B6-text">888</text>
</g>

问题:

  1. 来自文本元素的textContent 是动态的,它可能比长度短 3
  2. 在我的 SVG 中,我有很多 &lt;g id="CDT-B6-2"&gt;,但 ID 和位置不同
  3. 我对所有文本元素都使用了x="50%" y="50%",但它没有使文本对齐以&lt;g&gt; 元素为中心

【问题讨论】:

    标签: javascript svg


    【解决方案1】:

    您可以使用dominant-baseline: middletext-anchor: middle

    text {
      dominant-baseline: middle;
      text-anchor: middle;
    }
    
    rect {
      stroke: black;
      stroke-width: 2;
      fill: none;
    }
    <svg width="200" height="100">
      <g transform="translate(10 20)">
        <rect x="0" y="0" width="80" height="40" />
        <text x="40" y="20">888</text>
      </g>
      <g transform="translate(110 40)">
        <rect x="0" y="0" width="80" height="40" />
        <text x="40" y="20">888888</text>
      </g>
    </svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2022-10-30
      • 1970-01-01
      相关资源
      最近更新 更多