SVG viewBox Attribute: Definition and Usage

The viewBox attribute in an SVG element defines the position and dimensions of the user coordinate system, determining which portion of an SVG drawing is visible and how it scales to fit its container. By decoupling an SVG’s internal drawing coordinates from its actual display size (viewport), the viewBox makes vector graphics fully responsive and scalable across different screen resolutions and layouts without distortion.

The Syntax of viewBox

The viewBox attribute accepts a list of four whitespace- or comma-separated numbers:

<svg viewBox="min-x min-y width height" width="500" height="500">
    <!-- SVG elements -->
</svg>

Viewport vs. viewBox

Understanding the viewBox requires distinguishing between two concepts:

  1. The Viewport: Defined by the width and height attributes on the <svg> tag (or through CSS), the viewport is the physical “window” or box on the webpage where the SVG is rendered.
  2. The ViewBox: The internal canvas or coordinate grid drawn inside that window.

The viewBox acts like a camera lens. If the viewBox is smaller than the viewport, the graphic zooms in. If the viewBox is larger than the viewport, the graphic zooms out.

Key Functions and Benefits