DEV Community

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

Posted on

4 2

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay