How do you collapse unused row in a CSS grid?

Instead of this:

grid-template-rows: min-content auto

Try this:

grid-template-rows: min-content 1fr

With 1fr you’re telling the second row to consume any and all free space available in the column. Hence, when there is no content in the .first element, the .second element takes the space.

The problem with auto is that its length is relative to other grid items on the track. This means that it won’t always shrink-to-fit one particular item (like min-content is designed to do) and it won’t allow an item to disappear entirely if another item has some size (like you’re seeing in your code).

.grid  {
  display: grid;
  grid-template-rows: min-content 1fr; /* adjustment */
  grid-template-columns: 60% 40%;
  grid-template-areas: 
    "main first"
    "main last";
}

.first { grid-area: first; background-color: orange; }
.main  { grid-area: main;  background-color: aqua; }
.last  { grid-area: last;  background-color: lightgray; }
<div class="grid">
  <b class="first">Grant me revenge!</b>
  <b class="main">Arnold ipsum. Just bodies. I need your clothes, your boots, and your motorcycle. Grant me revenge! And if you do not listen, then to HELL with you. Make it quick because my horse is getting tired. Come on don't bullshit me. Into the tunnel. Bring your toy back to the carpet.</b>
  <b class="last">Make it quick because my horse is getting tired.</b>
</div>

<br>

<div class="grid">
  <b class="first"></b>
  <b class="main">Arnold ipsum. Just bodies. I need your clothes, your boots, and your motorcycle. Grant me revenge! And if you do not listen, then to HELL with you. Make it quick because my horse is getting tired. Come on don't bullshit me. Into the tunnel. Bring your toy back to the carpet.</b>
  <b class="last">Make it quick because my horse is getting tired.</b>
</div>

Leave a Comment