SVG height element not dynamic?
I am trying to change svg dynamically depending on the size of the browser.
<!DOCTYPE html>
<html lang="en">
<head>
<script type= 'text/javascript' src ='../libraries/d3/d3.v3.min.js'> </script>
<meta charset="UTF-8">
<title>CIQ workflow</title>
<style type='text/css'>
svg{
width:80%;
height:80%;
background:green;
}
</style>
</head>
<body>
<script >
var canvas = d3.select('body').append('svg')
</script>
</body>
</html>
When I view this specific code in a browser, it updates dynamically in width, but not in height. Why?
What is the advantage of using the viewport and then changing these values ββcompared to this methodology? Why the right way?
(1) Try adding
html{
height:100%;
}
body{
height:100%;
}
to your style, and your SVG will now look appropriate. What happens is that your page is document.bodymatched to the right content. Essentially, this is:
Check inner DOM elements to determine height
--> Sees SVG element and tries to size it based on that.
--> SVG element has no height set so set body to some browser-specified
body min-height
==> Onward to SVG element!
--> SVG height = 80% body min-height.
- , , 500px ( 10px, ).
(2) ViewBox, w3.org , , ViewBox , , ViewBox.
: , Safari Chrome , html{height:100%} , Firefox, , .
, SVG , viewBox Javascript, , .
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SVG Fills Window Screen</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style='overflow:hidden'>
<div id="svgDiv" style='position:absolute;top:0px;left:0px;background-color:lightgreen;'>
<svg id="mySVG">
<circle id="myCircle" cx="120" cy="180" r="40" fill="red" stroke="black" stroke-width="2" />
<rect id="myRect" x="220" y="250" width="60" height="60" fill="blue" stroke="black" stroke-width="2" />
<ellipse id="myEllipse1" cx="900" cy="1200" rx="150" ry="75" fill="yellow" stroke="black" stroke-width="2" />
<ellipse id="myEllipse2" cx="1900" cy="90" rx="150" ry="75" fill="yellow" stroke="black" stroke-width="2" />
<ellipse id="myEllipse3" cx="3900" cy="2200" rx="150" ry="75" fill="yellow" stroke="black" stroke-width="2" />
<text x="50%" y="50%" text-anchor="middle" font-size="150">SVG image fills window screen</text>
</svg>
</div>
<script id=myScript>
//--onload, onresize----
function sizeFull()
{
var svgW=window.innerWidth
var svgH=window.innerHeight
var bb=mySVG.getBBox()
var bbx=bb.x
var bby=bb.y
var bbw=bb.width
var bbh=bb.height
mySVG.setAttribute("viewBox",bbx+" "+bby+" "+bbw+" "+bbh )
mySVG.setAttribute("width",svgW)
mySVG.setAttribute("height",svgH)
}
document.addEventListener("onload",sizeFull(),false)
window.onresize=sizeFull
</script>
</body>
</html>