SVG viewBox padding

08 February 2023

Suppose there's a rect shape the same size as its SVG container. When you add stroke to it, the border of the rectangle you see is only half its actual width.

<svg viewBox="0 0 10 10">

The other half is outside the visible area of the SVG and gets clipped. You can change the overflow property to reveal it.

<svg overflow="visible">

To entirely put the rectangle within the visible area, either by repositioning the rectangle and reducing its size, or by adjusting the viewBox value as shown below.

<svg viewBox="-.5 -.5 11 11">


I was delighted to learn the other day, that a new property stroke-align is well documented in the SVG Working Draft. The inset value it provides is exactly what I'm looking for.

<rect stroke-align="inset" ... />

The bad news is that we do not know when it'll be available in the browser.


I then revisited the viewBox property and tried to find a way to simplify its modification. One idea was to extend the viewBox value to support padding.

viewBox="0 0 10 10 padding .5"

/* translates to */

viewBox="-.5 -.5 11 11"

This approach enhances readability and also simplifies debugging. I used to change four values of viewBox during testing, now only change one.

Better keyword?

While alternative keywords such as expand may be more precise, the name padding is more understandable for web developers, since changing viewBox to fit the content is visually similar to adding CSS paddings.


I have been gradually improving the new syntax introduced in my last blog post. The viewBox padding is one of recent updates.

Here is an example of using padding to ensure that all shapes are precisely contained within the viewable area of the SVG.

svg {
  viewBox: 0 0 10 10 padding .2;

  stroke: #000;
  stroke-width: .4;
  stroke-linecap: round;

  line*10x10 {
    x1, y1, x2, y2: @p(
      @nx(-1) @ny(-1) @nx @ny,
      @nx @ny(-1) @nx(-1) @ny,
      @nx @ny(-1) @nx @ny

Try it online.