How do you collapse unused row in a CSS grid?

后端 未结 1 1836
[愿得一人]
[愿得一人] 2020-12-07 00:26

So I have a simple stack of three paragraphs on mobile that I want to style in a grid on larger viewports, without changing the source order.

The first section might

相关标签:
1条回答
  • 2020-12-07 01:09

    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>

    0 讨论(0)
提交回复
热议问题