Resize svg when window is resized in d3.js Resize svg when window is resized in d3.js javascript javascript

Resize svg when window is resized in d3.js


Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.

Here is how I did it:

d3.select("div#chartId")   .append("div")   // Container class to make it responsive.   .classed("svg-container", true)    .append("svg")   // Responsive SVG needs these 2 attributes and no width and height attr.   .attr("preserveAspectRatio", "xMinYMin meet")   .attr("viewBox", "0 0 600 400")   // Class to make it responsive.   .classed("svg-content-responsive", true)   // Fill with a rectangle for visualization.   .append("rect")   .classed("rect", true)   .attr("width", 600)   .attr("height", 400);
.svg-container {  display: inline-block;  position: relative;  width: 100%;  padding-bottom: 100%; /* aspect ratio */  vertical-align: top;  overflow: hidden;}.svg-content-responsive {  display: inline-block;  position: absolute;  top: 10px;  left: 0;}svg .rect {  fill: gold;  stroke: steelblue;  stroke-width: 5px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="chartId"></div>