Expanding cells in CSS grid layout

前端 未结 2 2012
无人共我
无人共我 2020-12-12 04:06

I have the following HTML/CSS

相关标签:
2条回答
  • 2020-12-12 04:48

    This is something better suited to flexbox but if your structure is as simplistic as you indicate the only-child can be used here.

    .main {
      display: grid;
      grid-template-columns: 2fr 1fr;
      margin-bottom: 1em;
    }
    
    
    /* The following is not essential - for decoration purposes only */
    
    .left {
      background-color: green;
      height: 25vh;
    }
    
    .left:only-child {
      grid-column: 1 / -1;
    }
    
    .right {
      background-color: orange;
    }
    <div class="main">
      <div class="left">Left</div>
      <div class="right">Right</div>
    </div>
    
    <div class="main">
      <div class="left">Left</div>
    </div>

    0 讨论(0)
  • 2020-12-12 05:01

    You can rely on implicit grid creation:

    .main {
      display: grid;
      grid-template-columns: 2fr;
      grid-auto-columns:1fr; /* this will trigger when you add the "right" element */
      grid-auto-flow:column;
      margin:5px;
    }
    
    
    .left {
      background-color: green;
    }
    
    .right {
      background-color: orange;
    }
    <div class="main">
      <div class="left">Left</div>
      <div class="right">right</div>
    </div>
    
    <div class="main">
      <div class="left">Left</div>
    </div>

    It does also work if you want to remove left:

    .main {
      display: grid;
      grid-template-columns: 2fr;
      grid-auto-columns:1fr; /* this will trigger when you add the "left" element */
      grid-auto-flow:column;
      margin:5px;
    }
    
    
    .left {
      background-color: green;
      grid-column-end:1; /* added this */
    }
    
    .right {
      background-color: orange;
    }
    <div class="main">
      <div class="left">Left</div>
      <div class="right">right</div>
    </div>
    
    <div class="main">
      <div class="right">right</div>
    </div>

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