I’ve been trying to vertically align a tspan inside a span in SVG for a few hours now, with no success.
I’ve also tried using some suggestions from stackoverflow answers and questions with reference to dominant-baseline="middle"
and alignment-baseline="middle"
, but nothing happened.
What I have currently done after some trial and error is this code here:
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="66"
style="position: absolute; left: 0px; top: 0px; user-select: none;">
<rect width="200" height="66" x="0" y="0" fill="cyan"></rect>
<g>
<text class="t" x="30" y="30" xlink:space="preserve"
style="font-size: 10px; font-family: monospace" fill="black"
dominant-baseline="middle" alignment-baseline="middle">ISTRUE:
<tspan class="tt" dominant-baseline="central" alignment-baseline="middle"
fill="green" style="font-size: 20px;">YES</tspan></text>
</g>
</svg>
At the end "ISTRUE:" class="t"
has to be vertical aligned with "YES" class="tt"
inside class="t"
.
They have a different font size and may also have a different family-font
(for now it’s monospace
for both of them)
2
Answers
If you add x and y values ββto the tt class, it can be aligned vertically. You can see it in the code below. You can edit the spaces as you wish.
You can do without any
x y
positioning, by animating the text over apath
animateMotion
set `to dur=".001s" to display "immediatly"(text is displayed at 0,0 first)
keypoints="0.5,0.5"
to animate to halfway the path<g>
is animated, not the<text>
or rename the attribute
stroke
tono-stroke
(not a SVG attribute!)Note
Because that
id="guide"
is a global IDYou are going to run into trouble when you add multiple SVGs to the page.
That first ID will always be used by all SVGs using that
guide
.Easily avoided by wrapping your SVG in declarative shadowDOM
side-effect: now global CSS can not style the SVG
<svg-protected>
can be any name you want (with a hyphen!)