3

How can I align text in an SVG without having to do it manually. At the moment I have manually set the positioning of the text inside a rectangle. This is fine, until the value of the text changed and then It looks off and doesnt really work. Is there a way of automatically setting the text to be aligned in the center, similar to text-align:center so it becomes responsive according to the page?

    <svg width="170" height="80" >
        <rect width="150" height="70" stroke="#4f7f64" stroke-width="5" fill="white" />
        <text x="45" y="25" r="65" font-family="'futura-pt-n7', 'futura-pt' , Helvetica, Arial, sans-serif" font-size="18" fill="black" font-weight="bold"> Settled </text>
        <text x="30%" y="55" r="65" font-family="'futura-pt-n7', 'futura-pt' , Helvetica, Arial, sans-serif" font-size="18" fill="black" font-weight="bold"> @String.Format("{0:C0}", Model.ReportTotalData.Select(r => r.Settled).FirstOrDefault()) </text>
    </svg>
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Andrew Kilburn
  • 2,251
  • 6
  • 33
  • 65
  • possible duplicate of [How to place and center text in an SVG rectangle](http://stackoverflow.com/questions/5546346/how-to-place-and-center-text-in-an-svg-rectangle) – rr- Jul 20 '15 at 13:25

2 Answers2

0

In the end, I just went and used a simple CSS circle, much, much easier.

Andrew Kilburn
  • 2,251
  • 6
  • 33
  • 65
0

You can achieve a similar effect to text-align:center by using the text-anchor property like this:

  1. Position the text in the center of the element in which you want to have the centered text (you can use x="50%").
  2. Add text-anchor="middle" to the text so it is rendered in the geometric middle of the specified position.

Here is a working here based on your code:

<svg width="170" height="80" >
  <rect width="150" height="70" stroke="#4f7f64" stroke-width="5" fill="white" />
  <text id="myText" x="75" y="25" r="65" font-family="'futura-pt-n7', 'futura-pt' , Helvetica, Arial, sans-serif" font-size="18" fill="black" font-weight="bold" text-anchor="middle"> Settled </text>
  <text x="50%" y="55" r="65" font-family="'futura-pt-n7', 'futura-pt' , Helvetica, Arial, sans-serif" font-size="18" fill="black" font-weight="bold"  text-anchor="middle"> @String.Format("{0:C0}", Model.ReportTotalData.Select(r => r.Settled).FirstOrDefault()) </text>
</svg>

<div style="margin-top:20px;">
  <input type="text" id="inputText" value="Test" />
  <input type="button" value="Update Text" onclick="updateText()" />
</div>

<script>
  function updateText() {
    document.getElementById("myText").innerHTML = document.getElementById("inputText").value;
  }
</script>

As you can see, you can replace the text dynamically and it will remain centered within the rectangle.

Alvaro Montoro
  • 28,081
  • 7
  • 57
  • 86