Search code examples
htmlcssgridcss-grid

Prevent CSS Grid row from collapsing?


Codepen: https://codepen.io/truthseekers/pen/gOKWQZQ

I want "item c" to extend down one more row, but when I change the grid-row-end: from 3 to 4, the middle row "collapses". I'm not seeing any information on collapsing rows in CSS Grid so how am I supposed to fix this?

<h1>Grid 3 Layering Grid Items</h1>
      <p>demonstrate that grid items can overlap each other.</p>
      <div class="grid3 container">
        <div class="box a3">item a</div>
        <div class="box b3">item b</div>
        <div class="box c3">item c</div>
        <div class="box d3">item d</div>
        <div class="box e3">item e</div>
        <div class="box f3">item f</div>
      </div>
.box {
  border-radius: 5px;
  padding: 20px;
}

.grid3 {
  font-size: 150%;
  background-color: lightgray;
  grid-gap: 10px;
  display: grid;
  grid-template-columns: 100px 100px 100px 100px 100px;
}

.a3 {
  background-color: rgba(0, 255, 255, 0.5);
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 1;
  grid-column-end: 3;
}

.b3 {
  background-color: greenyellow;
  grid-column-start: 3;
  grid-column-end: 6;
  grid-row-start: 1;
  grid-row-end: 2;
}

.c3 {
  background-color: rgba(255, 165, 0, 0.5);
  grid-column-start: 1;
  grid-column-end: 2;
  grid-row-start: 2;
  grid-row-end: 3; /* Why does changing this to 4 cause the middle row to disappear?*/
}

.d3 {
  background-color: rgba(255, 0, 0, 0.5);
  grid-column-start: 2;
  grid-column-end: 5;
  grid-row-start: 1;
  grid-row-end: 3;
}

.e3 {
  background-color: rgba(255, 105, 180, 0.5);
  grid-column-start: 1;
  grid-column-end: 6;
  grid-row-start: 3;
  grid-row-end: 4;
}
.f3 {
  background-color: rgba(160, 32, 240, 0.5);
  grid-column-start: 3;
  grid-column-end: 6;
  grid-row-start: 2;
  grid-row-end: 4;
  z-index: 20;
}

In the class .c3 I'm unable to change the grid-row-end to 4 because that causes the entire middle row to collapse for some reason. How can I fix this?


Solution

  • So if you set c3 to span 2 rows, that would mean grid row 2 doesn't have to be responsible for any elements, so it will then shrink its height to auto, which kinda looks like "collapses". Either you set a grid-auto-rows on grid container or have at least one element placed in row 2 I think.

    .grid3 {
      /* ... */
      grid-auto-rows: 100px;
    }