I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments.
For horizontal alignment I can use text-anchor
with left
, middle
or right
. I can't find a equivalent for vertical alignment; alignment-baseline
doesn't seem to do it, so at present I'm using dy="0.5ex"
as a kludge for centre alignment.
Is there a proper manner for aligning with the vertical centre or top of the text?
If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ). Is there a way to not have to manually set height and width on the rect?
The <text> Element. In SVG, text is rendered with the <text> element. The simplest example of a <text> element is one that uses just x and y attributes to place it. Text is rendered by default with a black fill and no outline.
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).
It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags (see this thread). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute.
<path d="M10, 20 L17, 20" style="fill:none; color:black; stroke:black; stroke-width:1.00"/> <text fill="black" font-family="sans-serif" font-size="16" x="27" y="20" style="dominant-baseline: central;"> Vertical </text> <path d="M60, 40 L60, 47" style="fill:none; color:red; stroke:red; stroke-width:1.00"/> <text fill="red" font-family="sans-serif" font-size="16" x="60" y="70" style="text-anchor: middle;"> Horizontal </text> <path d="M60, 90 L60, 97" style="fill:none; color:blue; stroke:blue; stroke-width:1.00"/> <text fill="blue" font-family="sans-serif" font-size="16" x="60" y="97" style="text-anchor: middle; dominant-baseline: hanging;"> Bit of Both </text>
This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way).
This effect can indeed be achieved by setting alignment-baseline
to central
or middle
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With