How to make your D3.js projects responsive

annemariedufour

Anne-Marie Dufour

Posted on April 22, 2022

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!

💖 💪 🙅 🚩
annemariedufour
Anne-Marie Dufour

Posted on April 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Create Simple Chart With D3js
javascript Create Simple Chart With D3js

November 10, 2020