Mind the Gap – Hide a Column in CSS-Grid
How to collapse a column in a CSS grid layout and remove the gap.
I went through all evolutions of column based designs in web design. From
display:flex. For the last two, in order to collapse or hide a column a
display:none works well and keeps the layout intact.
With the CSS Grid, web designers got a powerful tool, that basically combines all past approaches, at least in terms of complexity.
While it is easy to setup a CSS grid layout, to make the visualized layout grid work, a lot of details in terms of how to describe the grid has to be learned. How do columns and row behave? How much space to they take?
All the things that were already complex in Flexbox (
flex-base and the likes) got even more complex in CSS Grid. But I'm not complaining - it's a wonderful tool.
Use Case and Pit Falls
For a 4 column grid, with gaps between the containers, a column in the middle can be collapsed like a vertical accordion. Nothing too fancy and a
display:none should do it.
In Flexbox the container disappears and all the other containers grow (depending on the setting of
Also the gaps get even out.
In CSS grid layout, one obstacle is, the column is not displayed anymore, but the space remains. That happens if a fixed value is set in the
grid-template-columns property. But even with something like
grid-template-columns: max-content - which makes the column collapse, the gap is still there.
The only solution I found so far is, to overwrite the grid
grid-template-columns and that makes some awkward css rules.
The following Codepen should illustrate the problem and offers a solution.
Here is a gist with the code: Mind the Gap - CSS Grid Hide a Column