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.)
Best Answer
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 thex
of that element + half its width (and similar fory
but with the height).Use the
text-anchor
property to center the text horizontally with the valuemiddle
:Use the
dominant-baseline
property to center the text vertically with the valuemiddle
(or depending on how you want it to look like, you may want to docentral
)Here is a simple demo: