Understanding SVG Coordinate Systems and Transformations — The viewport, viewBox, and preserveAspectRatio

Understanding SVG Coordinate Systems and Transformations — The viewport, viewBox, and preserveAspectRatio

SVG elements aren't governed by a CSS box model like HTML elements are. This makes positioning and transforming these elements trickier and may seem—at first glance—less intuitive. However, once you understand how SVG coordinate systems and transformations work, manipulating SVGs becomes a lot easier and makes a lot more sense. In this article we're going to go over three of the most important SVG attributes that control SVG coordinate systems: viewport, viewBox, and preserveAspectRatio.

This is the first in a series of three articles covering the topic of coordinate systems and transformations in SVG.

[…]

The canvas is the space or area where the SVG content is drawn. Conceptually, this canvas is infinite in both dimensions. The SVG can therefore be of any size. However, it is rendered on the screen relative to a finite region known as the viewport. Areas of the SVG that lie beyond the boundaries of the viewport are clipped off and not visible.

[…]

The SVG viewport is similar to the viewport of the browser you’re viewing this page through. A web page can be of any size; it can be wider than the viewport’s width, and is in most cases also longer than the viewport’s length. However, only portions of a web page are visible through the viewport at a time.

[…]

You specify the size of the viewport using the width and height attributes on the outermost <svg> element.

[…]

Note that the width of the viewport can also be set in CSS to any value. For example, setting width: 100% will make the SVG viewport fluid in a document. Whatever value of the viewBox, it will then be mapped to the computed width of the outer SVG element.

[…]

If you’ve read about the viewBox somewhere before, you may have come across a few definitions saying that you can use the viewBox attribute to transform the SVG graphic by scaling or translating it. This is true. I’m going to go further and say that you can even crop the SVG graphic using viewBox.

[…]

Anything you draw on the SVG canvas will be drawn relative to the new user coordinate system.

[…]

I hope you found this article useful in understanding the SVG viewport, viewBox, and preserveAspectRatio concepts. If you’d like to learn more about SVG coordinate systems, like nesting coordinate systems, establishing new ones, and transformations in SVG, stay tuned for the remaining parts of this series. You can subscribe to the RSS (link below) or follow me on Twitter to stay updated. Thank you very much for reading!

The SVG parrot illustration used is a freebie from Freepik.com.

[…]