score:2

tl;dr: viewBox is for drawing whats inside the SVG, width and height tell at what size to display it.

The viewBox defines the canvas and coordinate system you are drawing your SVG into. If it says viewBox="10 50 100 100", and you want to draw a square that covers the upper left quarter of your image, you'll write:

<svg viewBox="10 50 100 100" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="50" width="50" height="50" />
</svg>

Then, when you want to display your SVG, for example embeded into a html page, width and height tell at what size to display them, just like you would for an image tag:

<div>
  <svg width="250" height="250" viewBox="10 50 100 100"
       xmlns="http://www.w3.org/2000/svg">
    <rect x="10" y="50" width="50" height="50" />
  </svg>
</div>

If your SVG was saved as an external file drawing.svg, you could express the same effect as

<div>
  <img src="drawing.svg" width="250" height="250" />
</div>

In both cases, the square you have drawn would cover the upper left quarter of the image, but since the SVG is drawn at an overall size of 250px ✕ 250px, the square has a side length of 125px ✕ 125px.

In other words, if the width defined in the viewBox is a, and the width defined on the element is b, the effect is the same as scaling everything inside the SVG (horizontally) with a factor of b / a.

(That obviously opens up the question what happens when viewBox height is c, element height is d, and the ratios d / c ≠ b / a don't match? That is what the preserveAspectRatio attribute describes.)

Formally, every combination of width, height, viewBox and preserveAspectRatio can be written equivalently as a transform attribute. The algorithm for this is described here. (Note that for the <svg> element as used here in the example, the x and y attributes must always be 0.)


Related Query

More Query from same tag