I am learning svg from its official documents, there is such line. I don't get it, if it already has a width
and height
attribute, what is the point to specify it again in viewBox="0 0 1500 1000"
? It is says, "One px unit is defined to be equal to one user unit. Thus, a length of "5px" is the same as a length of "5"" in the official docs, thus this viewBox is a 1500px wide and 1000 height view, which exceeds 300px and 200px. So why does it define the width and height value in the first place?
<svg width="300px" height="200px" version="1.1" viewBox="0 0 1500 1000" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg">
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.
In order to change the value of the SVG viewport's width and height, we can use CSS. Simple. But to change the value of the viewBox , we currently need to use JavaScript. Not all SVG presentation attributes are available as CSS properties; only the set of attributes that have CSS property equivalents can be set in CSS.
The viewport is the visible area of the SVG image. An SVG image can logically be as wide and high as you want, but only a certain part of the image can be visible at a time. The area that is visible is called the viewport. You specify the size of the viewport using the width and height attributes of the <svg> element.
The width and height are how big the <svg>
is. The viewBox controls how its contents are displayed so the viewBox="0 0 1500 1000" will scale down the contents of <svg>
element by a factor of 5 (1500 / 300 = 5 and 1000 / 200 = 5) and the contents will be 1/5 the size they would be without the viewBox but the <svg>
Imagine you have an elastic surface and cut it into 4 equal pieces. If you throw 3 pieces away you've got a surface that's 1/4 the size of the original surface. If you now stretch the surface and make it the same size as the original surface then everything on the surface will be twice the size. That's how viewBox and width/height are related.
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