I am trying to position a <text>
element in HTML5 SVG by giving it a top margin. Let' say, I wanted the <text>
element to have a top margin of 10px. This will not work:
<svg style="height: 100px; border: 1px solid black">
<text fill="#000" x="10" y="10" font-size="50" font-family="Arial">
<tspan>The quick brown fox jumps over the lazy dog</tspan>
</text>
</svg>
The problem is, that for SVG text elements, the y
distance is measured from the bottom line of the text, not the top. This code produces text where only the lower 10px are visible. So, we have to add the font-size
value to the y
value to get the margin right:
<svg style="height: 100px; border: 1px solid black">
<text fill="#000" x="10" y="60" font-size="50" font-family="Arial">
<tspan>The quick brown fox jumps over the lazy dog</tspan>
</text>
</svg>
At least, that was what I thought. But this does not work either. Now, the top margin is too large, as you can see in the fiddle: http://jsfiddle.net/yy8gS/2/. I want the top margin to be the same as the left margin, which is clearly not the case. In fact, a y
value of 48 looks about right but I have no idea why, or how I could calculate this value for arbitrary margins and font sizes. It seems to me that the font-size
value is not the actual text height value used by SVG for positioning.
Can anybody help me with this? Is what I am trying to do even possible with SVG?
Thanks in advance!
An easy solution to center text horizontally and vertically in SVG: Set the position of the text to the absolute center of the element in which you want to center it: If it's the parent, you could just do x="50%" y ="50%" .
You could give the svg a class and position it absolutely on top with a z-index of -1, and then space your header-h2 accordingly.
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?
Setting dominant-baseline should give you what you need, perhaps dominant-baseline="hanging"
so that the text position is based on the top of the text rather than the baseline.
If you want to know how tall the font is then you should call getExtentOfChar to determine it rather than assuming you get a font with a font-size which is exactly what you asked for.
You can also use em
's in y
and dy
-attributes!
This solved my problem at least:
<div>
<p>working: margin as y-value:</p>
<svg style="height: 100px; border: 1px solid black">
<text fill="#000" x="10" y="1em" font-size="50" font-family="Arial">
<tspan>The quick brown fox jumps over the lazy dog</tspan>
</text>
</svg>
</div>
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