Mark13426
Mark13426

Reputation: 2639

Understanding SVG <text> x-y coordinates and padding

Fiddling with the following example:

<html>
<head>
    <style>
        html,body {
            width: 100%;
            height: 100%;
            margin: 0;
        }
    </style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
     width="1024px" height="1024px" viewBox="0 0 1024 1024" style="background-color: yellow">

    <text x="0" y="29"
          font-family="'Lucida Grande', sans-serif"
          font-size="32">

        Regular ol' text here. Hi.

    </text>

</svg>
</body>
</html>

When I inspect <text> in Chrome, it shows the height as 35.7969px. I'm not sure if this number is based on screen resolution/density or not.

Two questions:

1) What do the x and y coordinates of <text> represent?

2) Is there a way to remove the padding inside <text> so the text fits the element completely?

Upvotes: 4

Views: 7891

Answers (1)

seb
seb

Reputation: 4319

  1. To answer the question, what does x and y refer to:

It is the x,y coordinates of the text baseline start position (in the left bottom corner of the first char).

Open a browser that has SVG support, copy this HTML-code, read the comments:

<!-- box (x,y) = 500x500 -->
<svg width="500" height="500">
<rect x="0" y="0" width="500" height="500"/>

<!-- yellow text (x/2, 0) -->
<text x="250" y="0" font-family="serif" font-size="25"
 fill="yellow">Easy-peasy Easy-peasy</text>
 
<!-- green text (0, y/2)  -->
<text x="0" y="250" font-family="serif" font-size="25"
 fill="green">Easy-peasy Easy-peasy</text>
 
<!-- green line from (0, 0) to (x/2, y/2) = center-->
<line x1="0" y1="0" x2="250" y2="250" stroke="green"/>

<!-- red line from (x/2, y/2) = center to left side (0, 250)  to -->
<line x1="250" y1="250" x2="0" y2="250" stroke="red" stroke-width="2" stroke-linecap="round" stroke-dasharray="1, 3"/>

</svg>

Upvotes: 8

Related Questions