Published on

Relationship between `viewBox` and `preserveAspectRatio`

Authors
  • avatar
    Name
    hwahyeon
    Twitter

The viewBox defines the internal coordinate system of an SVG, but how the content appears on the screen is adjusted with the preserveAspectRatio attribute. For example, setting preserveAspectRatio="none" will ignore the aspect ratio defined by the viewBox and distort the content.

1. Maintaining Aspect Ratio

The content maintains its aspect ratio and is centered within the viewport. If the preserveAspectRatio attribute is not specified, the default value is preserveAspectRatio="xMidYMid meet".

<svg width="400" height="200" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
  <rect x="0" y="0" width="80" height="50" fill="pink" />
</svg>

2. Distorted Output

The content ignores its aspect ratio and fills the viewport completely, causing distortion.

<svg width="400" height="200" viewBox="0 0 100 100" preserveAspectRatio="none">
  <rect x="0" y="0" width="80" height="50" fill="pink" />
</svg>