Reputation: 47
In the first example, my code generates the text as much larger and the circle as slightly smaller than they are without the viewbox attribute. They are also centered in the middle.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body {
margin: 0;
padding: 0;
border: 0;
height: 100%
}
svg {
position: absolute;
margin: 0;
padding: 0;
border: 0;
}
</style>
</head>
<body>
<svg id="test" width="100%" height="auto" viewBox="0 0 100 100">
<text id="thisthing" x="10%" y="10%" class="small">this is test</text>/>
<circle id="circe" cx="5%" cy="6%" r="5%" stroke="green" stroke-width="1%" fill="yellow" />
</svg>
</body>
</html>
In the second example, the circle is slightly larger and the text is much smaller. They are in the left hand corner as intended.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body {
margin: 0;
padding: 0;
border: 0;
height: 100%
}
svg {
position: absolute;
margin: 0;
padding: 0;
border: 0;
}
</style>
</head>
<body>
<svg id="test" width="100%" height="auto" >
<text id="thisthing" x="10%" y="10%" class="small">this is test</text>/>
<circle id="circe" cx="5%" cy="6%" r="5%" stroke="green" stroke-width="1%" fill="yellow" />
</svg>
</body>
</html>
I am wondering what the purpose of the viewbox is and why it is creating this difference. My understanding is that the viewbox is supposed to help with svg percentage scaling, but it is operating differently than intended. The big issue is my svg objects are shifting to the middle and not in the intended position in the top left corner.
Upvotes: 1
Views: 280
Reputation: 21163
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
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. The numbers, which are separated by whitespace and/or a comma, specify a rectangle in user space which is mapped to the bounds of the viewport established for the associated SVG element (not the browser viewport).
<style>
svg{ width:30%; background:pink}
</style>
<svg>
<text x="10%" y="10%">this is test</text>/>
<circle cx="5%" cy="6%" r="5%" stroke="red"/>
</svg>
<svg viewBox="0 0 100 100">
<text x="10%" y="10%">this is test</text>/>
<circle cx="5%" cy="6%" r="5%" stroke="red"/>
</svg>
<svg viewBox="0 0 100 30">
<text x="20" y="20">this is test</text>/>
<circle cx="10" cy="15" r="5" stroke="red"/>
</svg>
Upvotes: 1