Search code examples
javascriptd3.jssvgresponsiveviewbox

responsive SVG using viewbox


I've managed to make a SVG responsive by using viewbox like this:

var svg = d3.select("#vis").append("svg") 
            .attr("width", "100%")
            .attr("height", "100%") 
            .attr("viewBox", "0 0 960 500")
            .attr("preserveAspectRatio", "none"); 

It's responsive and gets smaller as screen size gets smaller. The only problem is that the SVG is too big when loaded in maximum screen. Can I set a maximum size? So, it doesn't get too big once it reaches the maximum size even though screen is big.


Solution

  • Why not use CSS to give a max-width to the container?

    var svg = d3.select("#vis").append("svg")
      .attr("width", "100%")
      .attr("height", "100%")
      .attr("viewBox", "0 0 960 500")
      .attr("preserveAspectRatio", "none");
      
    svg.append('circle')
      .attr('r', 100)
      .attr('cx', 300)
      .attr('cy', 300)
    #vis {
      max-width: 960px;
      margin: 0 auto;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
    <div id="vis"></div>