18

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!

2 Answers 2

28

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.

3
  • dominant-baseline: hanging; Apr 4, 2017 at 10:37
  • 1
    text { dominant-baseline: text-before-edge; }
    – feiyuw
    May 19, 2020 at 11:18
  • I like this solution, however I found that it's not yet supported by Safari.
    – Nick Taras
    May 31, 2021 at 2:45
9

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.