Dynamic Number of Flexible Columns in CSS Grid Lanes

When I saw that display: grid-lanes was coming I realized I could soon get rid of my masonry JavaScript layout and enjoy browser-smooth layout instead. But I couldn't get what I wanted: a dynamic number of columns, where each column was at most MAX-WIDTH wide, but could shrink to MIN-WIDTH to fit more columns. After playing around a bit I came up with this:

<style>
#lane-container {
    container-type: inline-size;
}
#lanes {
    display: grid-lanes;
    repeat(
        /* 
         * number of columns is how many 
         * MIN-WIDTH will fit, but not more 
         * than the number of elements we 
         * have. (No empty columns.)
         */
        min(
            var(--num-elements),
            round(down, 100cqi / MIN-WIDTH)
        ), 
        /*
         * Do the usual minmax
         */
        minmax(MIN-WIDTH, MAX-WIDTH)
    );
    justify-content: center;
}
</style>
...
<div id="lane-container">        
    <div id="lanes" 
        style="--num-elements: NUM-ELEMENTS"
    >
    ...elements...
    </div>
</div>
  1. Set container-type: inline-size on lane-container, the container of the grid lane layout.

  2. Set --num-elements on the lanes, the layout, to cap the number of lanes to the number of elements.

  3. Finally, set grid-template-columns as above.

!

Your browser either doesn't support grid-lanes, or has it behind a flag. For Chrome, go to chrome://flags/ and search for "grid lanes" to enable it.

Width:

50

1
2
3
4
5
6