Search code examples
htmlcsscss-gridgrid-layout

How to achieve grid row with more than one element vertically?


I have a two column grid layout that holds boxes of heights X and 2X (fiddle, screenshot below)

Box number two has empty space underneath it, enough empty space to fit box 3:

ex

I want to know if it is possible to have card 3 placed in that empty space (and have card 4 take card 3's place, and card 5 take card 4's place)

I attempted this layout with flex, but I reached this same situation.

.boxes {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-column-gap: 25px;
  grid-row-gap: 25px;
}

.smallbox {
  border: 2px solid black;
  padding: 1em;
  height: 50px;
}

.bigbox {
  border: 1px solid black;
  padding: 1em;
  background: red;
  height: 150px;
}
<div class="boxes">
  <div class="bigbox">1</div>
  <div class="smallbox">2</div>
  <div class="smallbox">3</div>
  <div class="smallbox">4</div>
  <div class="smallbox">5</div>
</div>


Solution

  • Don't set the height on the grid items themselves.

    Use grid-auto-rows at the container level, then span for the grid areas.

    .boxes {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-auto-rows: 50px; /* new */
      grid-column-gap: 25px;
      grid-row-gap: 25px;
    }
    
    .smallbox {
      grid-row: span 1; /* new */
      border: 2px solid black;
      padding: 1em;
    }
    
    .bigbox {
      grid-row: span 3; /* new */
      border: 1px solid black;
      padding: 1em;
      background: red;
    }
    <div class="boxes">
      <div class="bigbox">1</div>
      <div class="smallbox">2</div>
      <div class="smallbox">3</div>
      <div class="smallbox">4</div>
      <div class="smallbox">5</div>
    </div>