How to Understand the Viewbox Attribute in SVG

A web design guide to using 'SVG' Viewbox (HTML)

SVG on iPad

mac steve / Flickr / CC BY 2.0

If you think of a web document as a canvas, the viewbox — an attribute of an SVG shape — is part of the canvas you want the viewer to see. Even though the page may cover the entire computer screen, the figure may only exist in a part of the whole.

Viewbox tells the parser to zoom in on that third. It eliminates the extra white space. Think of viewbox as a virtual approach to crop an image. Without it, your graphic will appear a third of its actual size.

'Viewbox' Values

To crop an image, you must create points on the picture to make the cuts. The same procedure is true with the viewbox attribute. The value settings for viewbox, which appear in space-separated syntax in a specific order, include

  • minx: the beginning x coordinate
  • miny: the beginning y coordinate
  • width: width of the viewbox
  • height: height of the viewbox

The syntax for viewbox values is:

viewbox="0 0 200 150"

This viewbox example creates a box at coordinates 0,0 with a width of 200 pixels and a height of 150 pixels.

Do not confuse the width and height of the viewbox with the width and height you set for the SVG document. When you create an SVG file, one of the first values you establish is the document width and height. The document is a canvas. The viewbox covers the entire canvas or just a portion of it.