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.)
An easy solution to center text horizontally and vertically in SVG:
Set the position of the text to the absolute center of the element in which you want to center it:
x="50%" y ="50%"
.x
would be the x
of that element + half its width (and similar for y
but with the height).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.
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>