1. Technology

Viewbox Attribute in SVG

Understanding the SVG Viewbox

By

SVG on iPad
mac steve/Flikr/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. This eliminates the extra white space. Think of view box as a virtual approach to crop an image. Without it, your graphic will appear 1/3 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 viewbox attribute. The value settings for viewbox include:

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

The syntax for viewbox 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 a 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.

<svg width="800" height="400" viewBox="0 0 800 400">

This view box covers the entire page.

<svg width="800" height="400" viewBox="0 0 400 200">

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

Your shape also has height and width assignments.

<svg width="800" height="400" viewBox="0 0 400 200">
<rect x="0" y="0" width="100" height="50" />

This is a document that cover 800 x 400 px with a view box that starts in the upper right hand corner and expands half of the page. The shape is a rectangle the 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 View Box?

SVG does much more than just draw a shape. 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.

  1. About.com
  2. Technology
  3. Web Design / HTML
  4. XML
  5. Specifications
  6. SVG
  7. Web Design: Understanding the SVG Viewbox

©2014 About.com. All rights reserved.