uaNiktia
uaNiktia

Reputation: 55

Why does the SVG preserveAspectRatio attribute work strangely?

I've created a simple example https://jsfiddle.net/7mupweLe/

<svg style="background:yellow" 
  height="200" width="200" viewBox="0 0 100 200" 
  preserveAspectRatio="xMidYMid meet">
    <rect class="rect" x="0" y="0" width="200" height="200" />
</svg>

Why is the black rectangle offset to the right this case. As I understand it, it must be in the exactly in the middle because I have xMidYMid.

Upvotes: 1

Views: 194

Answers (1)

Robert Longson
Robert Longson

Reputation: 123995

We've an area 200 x 200 px (the width and height of the <svg> element) in which we want to display something that's 100 x 200 (the viewBox)

The meet of preserveAspectRatio says make sure we display everything and have space on either the sides or the top (in this case the side). xMidYMid means make the space even.

So to the left and right of the viewBox we'll see the background except that the SVG contains a shape - a rect which is bigger than the viewBox 200 x 200 against the 100 x 200 of the viewBox and so it overflows the viewBox to the right hand side.

If we make the rect the same size as the viewBox, everything is symmetrical.

<svg style="background:yellow" 
  height="200" width="200" viewBox="0 0 100 200" 
  preserveAspectRatio="xMidYMid meet">
    <rect class="rect" width="100" height="200" />
</svg>

Upvotes: 1

Related Questions