Search code examples
htmlcsscss-grid

How do I make a CSS grid cell collapse when empty or using display:none?


TL;DR: Codepen https://codepen.io/veleek/pen/YmJGjY shows that grid cell with display: none seems to cause adjacent cell to take up less space instead of collapsing to nothing.

I'm creating a simple CSS Grid layout with a banner at the top with a logo, title, link bar, and a content block underneath.

Rough layout

For pages without nav links I'd like to collapse the nav section so that the title takes up the entire space. Effectively I want that grid cell to be 0px tall.

Unfortunately, when I set display: none on that cell, it disappears but it seems to take up MORE space. This actually causes the title to collapse itself down to be SMALLER then when that cell is present.

Title collapsing to be smaller

The image size is not fixed at 150px and I'd prefer to avoid fixed sizes if possible. I just want to force that grid row to have 0 height when it's empty. I've tried a bunch of combinations of display:block/flex, align-items/justify-content/etc.: stretch/center/etc. but nothing seems to work.

I've got a CodePen showing the issue here: https://codepen.io/veleek/pen/YmJGjY


Solution

  • The problem is related to the definition of auto for a grid row. According to grid-row-template MDN docs auto is:

    Is a keyword that is identical to maximal content if it's a maximum. As a minimum it represents the largest minimum size (as specified by min-width/min-height) of the grid items occupying the grid track.

    So when there is content in the track, it acts as a maximum and sizes correctly. But when there is no content in the clue-nav element, it appears to fallback to the minimum definition, and since the only grid item occupying the track is the image in clue-logo so the minimum ends up getting set to a much larger value. As everything resolves itself, the "empty" grid cell gets a bunch more space, and the clue-title grid cell ends up taking up the actual "minimum" amount of space that it needs.

    To work around this issue, instead of setting the height to auto, you can use minmax(0, auto). This allows the actual minimum height of the row to go to zero instead of the clue-logo height, and it properly collapses when clue-nav is hidden.

    I stumbled on this while fiddling around with Sølve's suggested answer, I noticed a bit more odd behavior around how it would decide to resize the row. So kudos to him for helping me stumble onto the right answer.