What is the viewBox in SVG and how it works

Key concept

The viewBox is one of the most important attributes of an SVG. It defines the internal coordinate system: which part of the drawing is shown and how it scales.

Syntax

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

Example: viewBox="0 0 100 100" creates an internal canvas of 100x100 units, with origin at the top-left corner.

viewBox vs width/height

If you set viewBox="0 0 100 100" and width="300", the 100-unit drawing stretches to 300px: 3x scale, without losing sharpness (it's vector).

Why it matters for scaling

With a viewBox and no fixed width/height, the SVG adapts to its container keeping proportions. That's why it's the foundation of a responsive SVG.

preserveAspectRatio

Controls how the drawing fits if the container has a different proportion:

Crop or reframe

Changing the viewBox reframes: viewBox="20 20 60 60" shows only that area, like a zoom/crop, without touching the shapes.

In the editor

In svgdesk, creating a canvas defines the viewBox based on the chosen size, and you see it in the code panel to adjust it.

Open the editor

Keep reading