Eduard Luca
Eduard Luca

Reputation: 6602

SVG text element not positioning correctly

I've set up a minimalist example of what I have here. I need to position the text element at the very top of the SVG. However if you inspect the text element, you'll see that it actually starts somewhere outside the SVG (like -3px on Chrome, -4px on FF) -- see below screenshot. I'm building something which needs to be pixel-perfect, so I need to get the text to start exactly where the SVG starts. As you can see, the rect starts where it's supposed to.

Since SO won't let me post links to jsfiddle without code inside the post, here's the code:

<svg width="100%" height="360" style="background-color: rgb(0, 249, 253);margin-top: 50px;">
  <rect y1="0" y2="100" x="0" width="100" height="100"></rect>
  <text x="100" y="0" dominant-baseline="hanging">2022</text>
</svg>

Any idea why this is happening?

enter image description here

Upvotes: 2

Views: 1404

Answers (1)

r3mainer
r3mainer

Reputation: 24547

According to the SVG specification, a dominant baseline of hanging is only meaningful for Indic scripts like Devanagari. If you want the top edge of the text box to align with a particular Y coordinate, then use text-before-edge instead:

<svg width="300" height="55" viewBox="0 0 300 55">
  <rect x="20" y="5" width="30" height="30" fill="#f00"/>
  <text x="50" y="5" dominant-baseline="hanging">8888</text>
  <text x="35" y="50" text-anchor="middle">hanging</text>
  <rect x="220" y="5" width="30" height="30" fill="#f00"/>
  <text x="250" y="5" dominant-baseline="text-before-edge">8888</text>
  <text x="235" y="50" text-anchor="middle">text-before-edge</text>
</svg>

Upvotes: 1

Related Questions