Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG - make viewBox(0, 0, 100%, 100%) with percentages

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.

like image 424
Tamara Jovic Avatar asked May 03 '18 13:05

Tamara Jovic


People also ask

Can you use percentages in SVG?

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 ).

How do I adjust SVG 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.

What is the viewBox property in SVG?

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 .

Does SVG need a viewBox?

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.


1 Answers

%/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/

like image 107
Fabian von Ellerts Avatar answered Sep 21 '22 22:09

Fabian von Ellerts