Why does reducing the size of an SVG viewBox make it's shapes bigger?

The SVG viewBox, at first glance, seems like a strange set of numbers.

While working with inline SVG, you may see a viewBox value that looks like this:


<svg height="100" width="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="50" fill="orange" />
</svg>

Which results in this perfect little circle:

Then you might think, "Ok, let's make this thing smaller. I'll reduce the height and width, and match up the viewBox along with it."


<svg height="50" width="50" viewBox="0 0 50 50">
  <circle cx="50" cy="50" r="50" fill="orange" />
</svg>

Weird huh? This baffled me too at first, while trying to fine tune some custom SVG icons.

As it turns out, the SVG viewBox is like a window onto a coordinate system.

The first two numbers represent the upper-left point (x and y) of the viewBox, while the second two numbers represent the lower-right point (max-x and max-y) of the viewBox.

The graphic above illustrates why reducing the viewBox results in only a portion of the circle to be visible.

So, how would you go about reducing the size of the shapes in an SVG, without reducing the overall size of the SVG?

Try some padding!

Here - I'm adding the CSS inline (normally I'd use a CSS class). I also added a background color for clarity.


<!-- With padding -->
<svg style="background-color: #e4e4e4; padding: 1em;" height="100" width="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="50" fill="orange" />
</svg>
<!-- Without Padding -->
<svg style="background-color: #e4e4e4;" height="100" width="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="50" fill="orange" />
</svg>

Want to continue improving your SVG and UI code-crafting skills? Sign up below.