Reputation: 531
Can anyone give me an example of how to vertically center multi-line text in SVG? I've googled and I see lots of references to alignment-baseline and dominant-baseline, but no concrete example for me to look at.
For example, in the following SVG, the TEXT element is locked by its top left-hand corner. Text starts appearing after that y position. What would I need to do if I wanted the text to be evenly distributed above and below that y position?
<text x="110" y="50" dy="0">
<tspan dy="0em" x="110" style="font-weight: bold; fill: rgb(74, 76, 77);">
<tspan x="110" dy="0em">This is my long quotation that will now wrap</tspan>
<tspan x="110" dy="1.1em">over multiple lines, maybe even two lines!</tspan>
<tspan x="110" dy="1.1em">Isn't that amazing?</tspan>
</tspan>
<tspan dy="1.5em" x="110" style="font-style: italic;">
Speaker, Speaker Description
</tspan>
</text>
(I'm generating this via D3, if that helps)
Upvotes: 5
Views: 4075
Reputation: 101800
You can't really do automatic centering with SVG. SVG has no proper automatic layout.
You can however use dy
, like you are doing, to position text relative to your baseline. Remember dy
can also be negative.
<svg width="400" height="150">
<line x1="110" y1="50" x2="400" y2="50" stroke="red"/>
<text x="110" y="50">
<tspan x="110" dy="-0.8em">This is my long quotation that will now wrap</tspan>
<tspan x="110" dy="1.1em">over multiple lines, maybe even two lines!</tspan>
<tspan x="110" dy="1.1em">Isn't that amazing?</tspan>
</text>
</svg>
The other thing you can do is use a <foreignObject>
element to embed HTML in your SVG. Obviously that only works in browsers.
Upvotes: 1