Search code examples
csscss-griddc.js

use CSS grid with dc-js?


I have been trying to use CSS grid layout with dc-js.

The graphs are defined without specifying a height and a width, letting the grid do its theoretical job.

I end up with something like the following image, where the graph ends up occupying only a third of the lateral space I had set for it in the grid layout. The svg within each individual graph's div still has default height and width set for some reason.

Is that the expected behaviour ?

If it isn't how do I solve this issue ?

EDIT : of course it works in this jsFiddle... I'm using dc version 3.0.12 if that helps.

enter image description here


Solution

  • Resizing and setting the width and height of a chart based on its container are not completely automatic in dc.js.

    As you discovered, the default width and height are 200. But you can cause the chart to calculate either one by passing a non-number such as null.

    This is partly for historical reasons and partly to provide more control. dc.js didn't have these features early on, and we usually try to add features in a backward-compatible way.

    If your grid changes size when the window changes size, you can add an onresize listener that causes every chart to resize the SVG to the same size as the chart div:

    window.onresize = function() {
        [chart1,chart2,chart3,chart4].forEach(
        c => {
          c.width(null).height(null).rescale();
          redraw_chart_no_transitions(c);
        });
    };
    

    If onresize is not to your taste, take a look at the resize observer scatter example for a more modern approach. You may need a resize observer if the grid will resize for another reason than window resize.

    redraw_chart_no_transitions is a small utility function available here that temporarily sets transitionDuration to zero so that redraw does not animate. Animated transitions are not good for actions that give immediate feedback like resize, pan, and zoom.

    I was able to reproduce the problem pictured in your question with your fiddle by making the window really large.

    To get the grid layout to use all the space I added the following CSS (not perfect, there's some stuff I don't understand here):

    html, body {
      position: absolute; top: 0; left: 0; right: 0; bottom: 0;
      margin: 1em;
    }
    
    #test {
      position: absolute; top: 0; left: 0; right: 0; bottom: 0;
      /* ... */
    }
    

    By default grid cells can get larger but not smaller. Specify min-width: 0 and min-height: 0 to allow them to get smaller:

    #test div {
      min-width: 0; min-height: 0;
    }
    

    Here is a fork of your fiddle with four charts that fill the window and resize when the window is resized.

    chart grid screenshot