SVG preserveAspectRatio Attribute Explained

The preserveAspectRatio attribute in SVG determines how a graphic scales and aligns when its viewBox aspect ratio does not match the aspect ratio of its viewport container. By default, vector graphics scale uniformly to fit within the designated area without distortion, but applying preserveAspectRatio allows developers to force distortion, crop excess areas, or align graphics precisely along the X and Y axes.

The Role of preserveAspectRatio

When defining an SVG, the viewBox sets the internal coordinate system and aspect ratio, while the width and height attributes define the outer viewport size. If the aspect ratios of these two systems differ, the browser must decide how to handle the mismatch. The preserveAspectRatio attribute dictates whether the graphic stretches to fill the space, maintains its proportions, and where it aligns inside the available viewport.

Syntax and Values

The attribute accepts one or two values formatted as:

preserveAspectRatio="<align> [<meetOrSlice>]"

1. The Alignment Parameter (<align>)

The <align> value controls both whether uniform scaling is applied and how the graphic aligns within the viewport.

The default value is xMidYMid, which centers the graphic both horizontally and vertically.

2. The Scaling Behavior Parameter (<meetOrSlice>)

When uniform scaling is active (any value other than none), the optional <meetOrSlice> parameter defines how the graphic fits the container:

Summary of Scaling Effects