How to place and center text in an SVG rectangle

An easy solution to center text horizontally and vertically in SVG:

  1. Set the position of the text to the absolute center of the element in which you want to center it:

    • If it’s the parent, you could just do x="50%" y ="50%".
    • If it’s another element, x would be the x of that element + half its width (and similar for y but with the height).
  2. Use the text-anchor property to center the text horizontally with the value middle:

    middle

    The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position.

  3. Use the dominant-baseline property to center the text vertically with the value middle (or depending on how you want it to look like, you may want to do central)

Here is a simple demo:

<svg width="200" height="100">
  <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>
  <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text>    
</svg>

You can also use this with CSS if you want to apply it to many elements. For example:

svg text{
  text-anchor: middle;
  dominant-baseline: middle;
}

Leave a Comment