CSS grid make items either span entire row or share space equally

Viewed 42

I want to build a grid that could, for example, look like this:

example grid

  • Each item is manually given its grid-row, for example the item D has grid-row: 6
  • If a row contains only one item, that item should span across the entire row, like the item A
  • If a row contains multiple items, or in other words the items "overlap", they should share the row's space equally, like items B and C or D, E and F
  • The grid-column property should NOT be given to items manually, for example I do not want to manually give the item F grid-column: 5 / 7. This is because items will be inserted into the grid one after the other, and when an item is inserted or removed the other items should adjust accordingly.

My current approach (that doesn't work) is this:

    .grid {
      height: 300px;
      width: 300px;
      display: grid;
      border: 1px solid red;
     }
     
     .item {
      border: 1px solid teal;
     }
     
     .item-a {
      grid-row: 1;
     }
     
     .item-b {
      grid-row: 2 / 4;
     }
     
     .item-c {
      grid-row: 3;
     }
    <div class="grid">
      <div class="item item-a">a</div>
      <div class="item item-b">b</div>
      <div class="item item-c">c</div>
    </div>

As you can see, the item a does not span across the entire row. Giving every item grid-column: span 2 just adds new columns and doesn't change the layout.

How can I achieve the desired grid?

0 Answers
Related