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!
2
Answers
@blaster god i think you will need to put both elements inside a wrapper. Set the wrapper to relative positioning. Then, set both elements to absolute positioning with top and left set to 0. Also, make sure the div’s line height is the same as its font size. Use the same font size and font family for both element and remove that extra a
First Line
First Line
I’m afraid you can only partially solve this task. Mainly due to SVG’s text-composing and layout limitations that make a perfect (responsive) replication of HTML elements quite impossible:
inline-size
get’s finalized in the W3C specs and adopted – I won’t hold my breath …)flex
orgrid
)In other words: to emulate/replicate HTML layouts in SVG we need to calculate suitable values via JavaScript.
Approach 1: inject SVG as inlined elements
We’re basically inheriting most of the the HTML font properties to the SVG
<text>
element as we’re rather injecting the SVG "lookalike" into the existing HTML/CSS layout context. Most notably we’re setting the SVG text-baseline to the bottom of theviewBox
and applyoverflow:visible
to clipped descenders or ascenders: the SVG element will move like a HTML text element respecting the inherited font-size.As you can see, we can reproduce the HTML text properties quite accurately… unless we get a line break.
The most simplistic SVG text replacement placeholder could be something like this:
SVG
The required CSS to make the SVG "float" on the baseline like regular text (and also inherit properties like text color) would be:
CSS
JS
Required to calculate a suitable
viewBox
widthApproach 2: Calculate y-offsets via
measureText()
for absolute positionWe can retrieve some vertical font metrics via
measureText()
to calculate suitable offsets for the SVG. See also "4.12.5.1.11 Drawing text to the bitmap"However, we still can’t emulate a line breaks.