2

This is the structure of my SVG

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

Problems:

  1. The textContent from text element is dynamic, it may shorter than length of 3
  2. Inside my SVG I have many <g id="CDT-B6-2"> but different ids & position
  3. I used x="50%" y="50%" to all text elements but it didn't put the text alignment centered from <g> element
Ghed Mendiola
  • 59
  • 2
  • 6

1 Answers1

2

You can use dominant-baseline: middle and text-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>
chrwahl
  • 8,675
  • 2
  • 20
  • 30