07. SVG preserveAspectRatio attribute

Along with viewBox, the preserveAspectRatio attribute let you control how the visible part of your SVG will be aligned.

To define the alignment, you have to set the x and y positions by using the keywords xMidYMid to center everything (this is the default). If you want everything aligned to the top left, use xMinYMin. And everything to the bottom right, use xMaxYMax.
There are 9 positions in total (3 for the x axis * 3 for the y axis).

Once you have defined the alignment, you can decide to let the browser crop your SVG or to always show the entire portion of the viewBox. To do so, you add the keyword slice or meet after the defined positions.
If you are familiar with background-size: cover/contain;, this is exactly the same. Using 'slice' will have the same effect as cover for a background. The browser will try to fill the dimensions with as much of your viewbox as possible. With 'meet', the browser will always make sure that your viewbox is fully visible and never cropped, just like 'cover'.

If you need more information, make sure to check the documentations on MDN.

Custom values for preserveAspectRatio

Try different values for the SVG below and see how the visual is being affected.

You can also resize the dimensions of the viewport and see how the browser is cropping (or not) your SVG.

<svg viewBox="0 0 200 100" preserveAspectRatio="xMidYMid meet">
	<rect fill="#ff0000" opacity="0.4" x="0" y="0" width="200" height="100" />
	<line x1="0" x2="200" y1="50" y2="50" />
	<line x1="100" x2="100" y1="0" y2="100" />
	<circle cx="0" cy="0" r="5" />
	<circle cx="200" cy="0" r="5" />
	<circle cx="200" cy="100" r="5" />
	<circle cx="0" cy="100" r="5" />
	<text x="0" y="0">{x:0, y:0}</text>
	<text x="200" y="0">{x:200, y:0}</text>
	<text x="200" y="100">{x:200, y:100}</text>
	<text x="0" y="100">{x:0, y:100}</text>
</svg>
{x:0, y:0} {x:200, y:0} {x:200, y:100} {x:0, y:100}

preserveAspectRatio="none"

There is a special value for the preserveAspectRatio attribute: none.

By setting none, you are telling the browser you don't care of the ratio of your SVG. It can be stretched in any direction.

The viewBox will fill 100% of the viewport by being stretched in both axis.

This value can be useful when you are using a path for a border or to add a little effect on a section (like a diagonal diagonal) and you want the path to fill the space.

<svg viewBox="0 0 200 100" preserveAspectRatio="none">
	<rect fill="#ff0000" opacity="0.4" x="0" y="0" width="200" height="100" />
	<line x1="0" x2="200" y1="50" y2="50" />
	<line x1="100" x2="100" y1="0" y2="100" />
	<circle cx="0" cy="0" r="5" />
	<circle cx="200" cy="0" r="5" />
	<circle cx="200" cy="100" r="5" />
	<circle cx="0" cy="100" r="5" />
	<text x="0" y="0">{x:0, y:0}</text>
	<text x="200" y="0">{x:200, y:0}</text>
	<text x="200" y="100">{x:200, y:100}</text>
	<text x="0" y="100">{x:0, y:100}</text>
</svg>
{x:0, y:0} {x:200, y:0} {x:200, y:100} {x:0, y:100}