Reputation: 239
How can I make SVG viewBox user coordinate system the same as the viewport coordinates system provided by SVG itself (height="100%" and width="100%")?
I need this special case for a project I'm doing, SVG element should be responsive, but still we need to keep height and width 100% on the SVG itself.
So, I need something like this:
<svg height="100%" width="100%" viewBox="0, 0, 100%, 100%">
<circle cx="25" cy="25" r="20" stroke="black" strokeWidth="1" fill="black" />
</svg>
.. but the viewBox attribute doesn't accept percentages.
Upvotes: 22
Views: 35576
Reputation: 5201
%/px is not allowed in the viewBox, those are the maximum coordinates.
By default the SVG content is contained to the SVG size.
If you want the content to stretch to 100%, disable the aspect ratio using preserveAspectRatio="none"
.
You can also use preserveAspectRatio="slice"
to make the content cover the SVG (like background-size: cover
).
<svg height="100%" width="100%" viewBox="0 0 100 100" preserveAspectRatio="none">
There are some good articles about this: https://css-tricks.com/scale-svg/ and https://alligator.io/svg/preserve-aspect-ratio/
Upvotes: 35