I have a SVG with width and height set to 100% and the property "preserveAspectRatio" is set to "xMidYMid meet".
With google chrome, after adding tag (Making it HTML5) the behavior changes. The SVG element does not occupy all the space on page, and height of SVG is set in proportion to width automatically.
HTML without DOCTYPE - Working as expected
<html>
<head>
<style>
body{
padding:0;
margin:0;
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1"
style="width:100%;height:100%;background-color:#0f0"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 100 150">
<rect
x="11"
y="11"
width="80"
height="130"
style="stroke: #000000; fill:none;"/>
</svg>
</body>
</html>
HTML with DOCTYPE - Not working
<!DOCTYPE HTML>
<html>
<head>
<style>
body{
padding:0;
margin:0;
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
version="1.1"
style="width:100%;height:100%;background-color:#f00"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 100 150">
<rect
x="11"
y="11"
width="80"
height="130"
style="stroke: #000000; fill:none;"/>
</svg>
</body>
</html>
Note :: The inline results snippets may be incorrect refer Plunker
Plunker Without DocType
Plunker With DocType
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 ).
SVG's exported from Illustrator CC are 'responsive' by default, in other words there is no height or width attributes, no dimensions. This can be great, but sometimes you may want to force dimensions. Say for example you want to use an SVG for a logo on your website, but you want it to be a set size.
Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .
Height % is based on it's parent (so you have to set every element above the target element to 100%) , there are a few workarounds to this though. For instance you can set it to height: 100vh; This will create the element to be 100% of your window height. Or you can use px instead.
If you set the width and height of the html and body elements you can get either result regardless of the presence of the html DOCTYPE
body, html {
padding:0;
margin:0;
height: auto;
width: 100%;
}
or
body, html {
padding:0;
margin:0;
height: 100%;
width: 100%;
}
legacy rendering simply has a different default for the default html height property. Both cases "work" provided you understand that, it's just a case of which one you want.
You may also want to make the svg element display: block e.g.
svg {
display: block;
}
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