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.
none: Disables uniform scaling. The graphic stretches non-uniformly along both axes to completely fill the width and height of the viewport, often causing visual distortion.- Uniform Alignment Values: When not set to
none, the value is a combination of an X-axis alignment (xMin,xMid,xMax) and a Y-axis alignment (YMin,YMid,YMax).xMin/YMin: Aligns the graphic to the top/left edge.xMid/YMid: Centers the graphic along the respective axis.xMax/YMax: Aligns the graphic to the bottom/right edge.
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:
meet(Default): Scales the graphic up or down so that the entireviewBoxis visible within the viewport while preserving its aspect ratio. If the ratios do not match, empty space (letterboxing or pillarboxing) will appear along the shorter dimension. This behavior is equivalent to CSSobject-fit: contain.slice: Scales the graphic uniformly until the entire viewport is covered by theviewBox. Any parts of the graphic that extend beyond the viewport boundaries are clipped. This behavior is equivalent to CSSobject-fit: cover.
Summary of Scaling Effects
preserveAspectRatio="none": Stretches the image to fill 100% of the viewport width and height, ignoring aspect ratio.preserveAspectRatio="xMidYMid meet": Preserves proportions, fits the entire graphic inside the viewport, and centers it.preserveAspectRatio="xMidYMid slice": Preserves proportions, scales to fill the entire viewport, centers the graphic, and crops the overflow.