Understanding the SVG viewBox attribute and why it's essential for responsive vector graphics.

The viewBox attribute is the most important and most misunderstood attribute in SVG. Understanding it is essential for making SVGs scale correctly.

What viewBox Does

The viewBox defines the coordinate system inside the SVG. It tells the browser: "this SVG's internal coordinate space runs from (min-x, min-y) to (min-x + width, min-y + height)." The browser then maps this internal space to whatever display size the SVG is rendered at.

The Syntax

viewBox="min-x min-y width height"

Example: viewBox="0 0 100 100" means the internal coordinate space is a 100×100 unit square starting at the origin.

Why It Matters for Scaling

Without a viewBox, SVG uses fixed pixel dimensions and doesn't scale responsively. With a viewBox, the SVG scales to fill its container while maintaining aspect ratio — exactly like a photograph scales inside an <img> tag.

Common Patterns

  • Responsive SVG: Set viewBox, remove width/height attributes, let CSS control the display size
  • Fixed-size SVG: Set both viewBox and explicit width/height attributes
  • Cropping: Adjust min-x and min-y to pan the visible area

When you convert PNG to SVG, the output SVG includes a viewBox matching the original image dimensions, ensuring correct scaling.