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.
Nearly every length measurement in SVG can be expressed by a percentage. With a few exceptions, those percentages are relative to the SVG coordinate system size—the size defined by the viewBox of the nearest ancestor <svg> or <symbol> (or by its actual width and height, if it doesn't have a viewBox ).
Values of width and height: With the width and height values you can change the size of the SVG vector. So, if we want to change the size and make it larger, then set the value for width and height, in viewBox, smaller then the width and height properties of the SVG element.
The viewBox attribute defines the position and dimension, in user space, of an SVG viewport. The value of the viewBox attribute is a list of four numbers: min-x , min-y , width and height .
viewbox is like a second set of virtual coordinates – all vectors inside the SVG will use the viewbox, while you can manipulate the actual height, width properties of the SVG without affecting the inside,. An SVG with a viewBox is so much easier to work with. I would never put an SVG together without one.
%/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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With