SVG viewBox and Path Scaling: Coordinate Systems Explained

Learn how the SVG viewBox attribute works with path coordinates. Understand how to scale, center, and crop SVG paths for responsive web design.

Optimization

Detailed Explanation

SVG viewBox and Path Scaling

The viewBox attribute defines the internal coordinate system of an SVG element. It determines how path coordinates map to the actual pixel dimensions on screen.

Syntax

<svg viewBox="min-x min-y width height" width="..." height="...">

Example

<svg viewBox="0 0 100 100" width="200" height="200">
  <path d="M 10,10 L 90,10 L 90,90 L 10,90 Z" />
</svg>

The path coordinates use the 0-100 viewBox system. The SVG is rendered at 200x200 pixels, so each viewBox unit equals 2 pixels. The path becomes a rectangle from (20,20) to (180,180) in screen pixels.

Fitting a Path to the ViewBox

After designing a path, calculate its bounding box and set the viewBox to match:

# Path bounding box: x=10, y=5, width=80, height=90
<svg viewBox="10 5 80 90">
  <path d="..." />
</svg>

This removes whitespace around the path and makes it fill the SVG element.

Adding Padding

To add padding around the path, expand the viewBox:

# 5 units of padding on each side:
<svg viewBox="5 0 90 100">

preserveAspectRatio

By default, SVG preserves the aspect ratio when the viewBox proportions differ from the element dimensions. Control this with:

<svg viewBox="0 0 100 50" width="200" height="200"
     preserveAspectRatio="xMidYMid meet">
Value Behavior
meet Scale to fit, maintain aspect ratio (letterbox)
slice Scale to fill, maintain aspect ratio (crop)
none Stretch to fill (distort)

Responsive SVGs

For responsive behavior, omit the width and height attributes and let CSS control the size:

svg { width: 100%; height: auto; }

The viewBox ensures the internal coordinates scale proportionally.

Use Case

Understanding viewBox is critical for creating responsive SVG icons, building icon sprite sheets, embedding SVGs in CSS as data URIs, and ensuring crisp rendering across screen densities (retina displays).

Try It — SVG Path Editor

Open full tool