DEV Community

Cover image for How to make your D3.js projects responsive
Anne-Marie Dufour
Anne-Marie Dufour

Posted on

How to make your D3.js projects responsive

A quick tip to make your D3.js projects responsive.

1- Set the viewBox attribute of the SVG parent: the first two values to zero, the last two to the width and height of your project, in pixels. It will ensure that the width/height ratio is maintained on all screen sizes.
Omit the width and height attributes since they will give fixed width and height to your project.

<svg viewBox="0 0 700 500">
  // Your viz goes here
</svg>
Enter fullscreen mode Exit fullscreen mode


2- Wrap the SVG parent in a responsive container.
There are many ways to go about it. For simplicity, I used a div element with 100% width and a max-width of 700px that corresponds to the max-width of the page content. Any grid system will also work.

<div style="width:100%; max-width:700px;">
  <svg viewBox="0 0 700 500"></svg>
</div>
Enter fullscreen mode Exit fullscreen mode


Hope that helps!

Top comments (0)