Skip to content

Instantly share code, notes, and snippets.

@drewbo
Created July 14, 2014 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drewbo/d733f639e79a73d5609a to your computer and use it in GitHub Desktop.
Save drewbo/d733f639e79a73d5609a to your computer and use it in GitHub Desktop.
Resizing D3 SVG

How to create D3 visualizations that resize and scale well

When creating the SVG, add this bit of D3:

.attr("id","chart")
.attr("viewBox","0 0 960 500")
.attr("perserveAspectRatio","xMinYMid")

Then later in the code, add this bit of jQuery:

var chart = $("#chart"),
    aspect = chart.width() / chart.height(),
    container = chart.parent();
$(window).on("resize", function() {
    var targetWidth = container.width();
    chart.attr("width", targetWidth);
    chart.attr("height", Math.round(targetWidth / aspect));
}).trigger("resize");

The end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment