I need to output multiple lines of text in SVG. For that I'm using the following scheme:
<text>
<tspan> First line </tspan>
<tspan> Second line </tspan>
</text>
First and second line of the text can have different number of characters, which can change dynamically. I want the second line to appear under the first line and text in both of them to be centered.
I can make second line appear below the first line by adding dy="15"
for the second <tspan>
.
I can align the text in each individual <tspan>
by adding text-anchor="middle"
to it.
But how to do relative centric alignment of those <tspan>
's?
I tried to use x="0"
for each <tspan>
but apparently it doesn't work since each <tspan>
has different width and the rendered text in the shorter line is shifted to the left.
Is there a way to align centres of 2 <tspan>
's of different width using only CSS and/or SVG.
If you add text-anchor="middle"
to each tspan
you will center them (you have to remove the space between the tspans as well, otherwise the extra space will be considered as part of the first line and they won't be completely centered).
For example:
<svg>
<text y="50" transform="translate(100)">
<tspan x="0" text-anchor="middle">000012340000</tspan><tspan x="0" text-anchor="middle" dy="15">1234</tspan>
</text>
</svg>
See: JSFiddle