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:
- If it’s the parent, you could just do
x="50%" y ="50%"
. - If it’s another element,
x
would be thex
of that element + half its width (and similar fory
but with the height).
- If it’s the parent, you could just do
-
Use the
text-anchor
property to center the text horizontally with the valuemiddle
: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 valuemiddle
(or depending on how you want it to look like, you may want to docentral
)
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;
}