DanilGholtsman
DanilGholtsman

Reputation: 2374

SVG text above rect strange layout

I try to make SVG text (wrapped in <text> of course) place on SVG <rect>.

And I want to make it look like text centered in my rect.

But strange thing I got there, it looks not like I assumed.

It looks like this

enter image description here

When I assumed it gonna be look like that

enter image description here

Whats wrong with that?

First I tought that equal x and y in <text> and <rect> will work, but it was like in picture below

enter image description here

I tought that y="50%" in text will force text to ancor somewhere in the middle. But I can achieve in only at y="80%" as you can see.

Original markup is here

<svg height="500" width="500" class="ng-scope">

  <svg height="50" width="393.703125" y="0">

    <g>
      <rect x="0" y="0" height="50" width="393.703125" style="fill: #A8A8A8">
      </rect>
      <text font-family="Airal" font-size="45" x="0" y="50%" inline-size="200">
        TEST TEXT IN SVG
      </text>
    </g>
  </svg>

</svg>

Upvotes: 3

Views: 543

Answers (2)

Sanket Patel
Sanket Patel

Reputation: 283

add viewBox. Again i am not expert at svg , have done just some work but this may work.

<svg height="500" width="500" class="ng-scope">

  <svg height="50" width="393.703125" y="0" viewBox="0 0 90 90">

    <g>
      <rect x="0" y="0" height="50" width="393.703125" style="fill: #A8A8A8" >
      </rect>
      <text font-family="Airal" font-size="45" x="0" y="50%" inline-size="200">
        TEST TEXT IN SVG
      </text>
    </g>
  </svg>

</svg>

Upvotes: 2

andreas
andreas

Reputation: 16936

The y property is per default applied to the text bottom line - so there is a difference between the y-position of a text and the y-position of lines, rectangles, or other shapes.

You can use the alignment-baseline property e.g. with middle to achieve better results. Here's the w3c description with many more options.

<svg height="500" width="500" class="ng-scope">

  <svg height="50" width="393.703125" y="0">

    <g>
      <rect x="0" y="0" height="50" width="393.703125" style="fill: #A8A8A8">
      </rect>
      <text font-family="Airal" font-size="45" x="0" y="50%" inline-size="200" alignment-baseline="middle">
        TEST TEXT IN SVG
      </text>
    </g>
  </svg>

</svg>

Upvotes: 3

Related Questions