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.
DEMO
text-anchor='start'
for right align.text-anchor='middle'
for middle align.text-anchor='end'
for left align.Code from demo:
Read more about text-anchor property here
Key points to horizontally centering the text:
1.
x="50%"
2.
text-anchor='middle'
In your case, you may write as:
If you add
text-anchor="middle"
to eachtspan
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:
See: JSFiddle