How to place and center text in an SVG rectangle

Lady Aleena picture Lady Aleena · Apr 5, 2011 · Viewed 181.9k times · Source

I have the following rectangle...

<rect x="0px" y="0px" width="60px" height="20px"/>

I would like to center the word "Fiction" inside of it. For other rectangles, does svg word wrap to stay within them? I can't seem to find anything specifically about inserting text within shapes that are centered both horizontally and vertically and word wrap. Also, the text can not leave the rectangle.

Looking at the http://www.w3.org/TR/SVG/text.html#TextElement example doesn't help since the text element's x and y are different from the rectangle's x and y. There doesn't seem to be width and height for text elements. I am not sure of the math here.

(My html table is just not going to work.)

Answer

Alvaro Montoro picture Alvaro Montoro · Jul 20, 2015

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>