Search code examples
svgcoordinate-systemsviewbox

What's the magic behind the SVG viewBox attribute?


After several trials there is something about the SVG viewBox I still don't understand. If I remove the viewBox from the following sample, the output becomes smaller. Why is this so? I know the viewBox scales to fit, but I don't see there is anything to scale. The extents of the path exactly match the width/height of the svg:

<svg width=595pt height=806pt  viewBox="0 0 595 806" overflow="visible">
<g style="
fill: none;
stroke: red; "  > 
    <path d="
      M  0.000 0.000
      L  595.000 806
      L  595.000 0.000
      L  0.000 806
 "/>
</g>
</svg>

Try it yourself here: https://jsfiddle.net/7zomyrp9/


Solution

  • The viewBox says that the we map 595 pixels into 595 points in the x direction. Per the CSS3 specification

    1pt = 1/72th of 1in
    1px = 1/96th of 1in

    So the px:pt ratio is 96:72 or 1.3333333:1

    So when you remove the viewBox the size of the drawing changes by that factor.

    The same reasoning applies to the y scaling.