ProgrammedChem
ProgrammedChem

Reputation: 157

SVG center text

I have the following:

<html>
  <svg height="500" width="500">
    <g id="avg-items">
    <rect
       ry="12.284702"
       rx="14.016526"
       y="186.2337"
       x="355.86771"
       height="96.626312"
       width="140.22598"
       id="basket-label"
       style="display:inline;opacity:0.76999996;fill:#ff0000;stroke:none" >
    </rect>     
    <text
      id="avg-item-num"
      text-anchor="middle">8</text>
  </g>
 </svg>
</html>

According to this, my text should be centered in the rect. But that is not the case. Any tips are appreciated! Thanks!

As per comment, I tried the following:

<html>
<svg height="500" width="500">
    <g id="avg-items">
    <rect
       height="96.626312"
       width="140.22598"
       id="basket-label"
       style="display:inline;opacity:0.76999996;fill:#ff0000;stroke:none">
    </rect>     
    <text
      id="avg-item-num"
      text-anchor="middle">8</text>
  </g>
 </svg>
</html>

But it still was not centered.

Upvotes: 2

Views: 720

Answers (1)

Robert Longson
Robert Longson

Reputation: 124049

You must draw your rect centred on the origin if you aren't going to supply and x/y values for the text. I've roughly divided the width/height by 2 and made them negative to show that below.

  <svg height="500" width="500" viewBox="-70 -48 500 500">
    <g id="avg-items">
    <rect
       ry="12.284702"
       rx="14.016526"
       x = "-70"
       y = "-48"
       height="96.626312"
       width="140.22598"
       id="basket-label"
       style="display:inline;opacity:0.76999996;fill:#ff0000;stroke:none" >
    </rect>     
    <text
      id="avg-item-num"
      text-anchor="middle">8</text>
  </g>

Upvotes: 1

Related Questions