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

Viewbox is an attribute commonly used when creating SVG shapes. If you think of the document as a canvas, the view box 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 third of the whole.

Viewbox allows you to tell 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 is true when using the view box attribute. The value settings for viewbox include:

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

The syntax for view box values is:

viewBox="0 0 200 150"

Do not confuse the width and height of the view box 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 view box can cover the entire canvas or just a portion of it.

This view box covers the entire page.

This view box covers half the page starting in the upper right-hand corner.

Your shape also has height and width assignments.

It is a document that covers 800 x 400 px with a viewbox that starts in the upper right-hand corner and expands half of the page. The shape is a rectangle that begins in the upper right-hand corner of the view box and moves 100 px to the left and 50 px down.

Why Set a Viewbox?

SVG does much more than just draw a shape. SVG can be used in web design. It can create one figure on top of another for a shadow effect. It can transform a shape so that it tilts in one direction. For the advanced filters, you will need to understand and use the viewbox attribute.