— by Nils
The viewBox
attribute is one of the most important attributes in SVG. It defines the coordinate system of the SVG and is used to scale and position the SVG contents inside the viewport.
preserveAspectRatio
is another important attribute that defines how the SVG should be scaled and positioned inside the viewport, similar to background-size: contain/cover
and background-position
.
Links
- MDN: viewBox
- SVG Viewport and viewBox (For Complete Beginners)
- Interactive tool to demo
preserveAspectRatio
Session CodePen
Browser Support
Every browser supports the viewBox
and preserveAspectRatio
attributes since their first version. Except if you want to support IE8. Which you shouldn’t.