How to use the <svg> viewBox attribute?

If you don't specify a viewbox, all unitless numbers in an element are assumed to be pixels. (and SVG assumes 90 dpi or pixels per inch for conversion from units like cm to pixels.)

A viewbox lets you make unitless numbers in elements mean "user units" and specifies how those units are mapped to the size. For simplicity, consider just the x coordinates, that is, a ruler. Your viewbox says that your ruler will have 1500 units to match the 200 pixel size width of the svg.

A line element from 0 to 1500 (unitless, i.e. user units) would stretch 200 pixels as drawn, that is, across the width of the svg drawing.

(And since SVG is scalable without loss of resolution, pixels really don't mean much in the real world, when a user zooms in or out.)

Its a coordinate transformation, of sorts.

I suggest you learn from a book like "SVG Essentials", about $10 used, from which I loosely quote this answer.


The width and height are how big the <svg> is. The viewBox controls how its contents are displayed so the viewBox="0 0 1500 1000" will scale down the contents of <svg> element by a factor of 5 (1500 / 300 = 5 and 1000 / 200 = 5) and the contents will be 1/5 the size they would be without the viewBox but the <svg>

Imagine you have an elastic surface and cut it into 4 equal pieces. If you throw 3 pieces away you've got a surface that's 1/4 the size of the original surface. If you now stretch the surface and make it the same size as the original surface then everything on the surface will be twice the size. That's how viewBox and width/height are related.

Tags:

Svg