svgviewbox

Why does an svg with viewbox of different ratio to dimensions renders element in center?


I am trying to understand why in the following svg the element appears in the center

<svg xmlns="http://www.w3.org/2000/svg"
     width="400" height="100"
     viewBox="0 0 100 100"
     style="outline: 1px solid green"
>
    <rect x="0" y="0" width="75" height="100" fill="#2222FF"  stroke="green"/>
</svg>
  

My understanding is that viewBox would take the box defined by the coordinates 0,0 - 100,100 on the svg and map it to the 400x100 image. So that should give me a top-to-bottom rectangle that reaches 3/4 of the way across. At the very least I would expect the rectangle to be all the way on the left.

I cannot for the life of me understand why the rectangle here appears in the center. What is going on?


Solution

  • Because the default preserveAspectRatio is xMidYMid.