javascripthtmlsvgdomcss-position

Position SVG <text> in identical position as HTML <div> with text inside


I am trying to position a svg with text in exactly the same position as div with text, no matter the font family used or font size

The problem comes with the first element being offset in x and y position.

I am trying to set both elements in top 0 left 0 absolute position but they fail to match .

Of course manually adding correct offset x and y works, but I want a general solution.

Here is an example that if you run, the texts won’t be positioned correctly one on top of another. I am trying to make this work with any font, any size.

<div style="position:absolute;color:red;font-family:Verdana;font-size:20px; margin-left:0; padding-left:0; left:0; ">
  First Line
</div>
<div style="position:absolute;top:0;left :0; background:transparent;"> 
<svg width="100" height="20" xmlns="http://www.w3.org/2000/svg">
<text x="0" y="0" font-family="Verdana" text-anchor="start" dominant-baseline="hanging" font-size="20" fill="black">First Line</text>
</svg>
</div>

Here is a codepen also https://codepen.io/Cristian-M/pen/VwJzXJv

Modifying the font size (make it bigger) and the offset is visible more and more

Any ideas? Thanks!


Solution

  • Doing tests, it seems I found the solution. If you want to have the SVG <text identical to dom <div text, what you need to do is set:

    dominant-baseline="center" (not middle, not hanging or any other).

    Example:

    <svg  width="300" height="300" xmlns="http://www.w3.org/2000/svg">
    <text x="0" y="40px" font-family="verdana" text-anchor="start" font-size="80px" dominant-baseline="central"   fill="black">First Line</text>
      <text x="0" y="120px" font-family="verdana" text-anchor="start" font-size="80px" dominant-baseline="central"   fill="black">Second Line</text>
    </svg>
    

    And you need to set the text Y position, to be half the font size

    here is a code pen showing the easy solution: https://codepen.io/Cristian-M/pen/VwJzxmK