htmlcsscss-grid

Make a grid item span to the last row / column in implicit grid


Is it possible to make a grid item span from the first to the last row when I don't know the number of rows?

Let’s say I have the following HTML content with an unknown number of boxes.

How can I make the third .box span from the first grid-line to the last?

.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(10rem, 1fr)) [last-col] 35%;
  grid-template-rows: auto [last-line];
}

.box {
  background-color: blue;
  padding: 20px;
  border: 1px solid red;
}

.box:nth-child(3) {
  background-color: yellow;
  grid-column: last-col / span 1;
  grid-row: 1 / last-line;
}
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box">3</div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


Solution

  • You can add grid-row-start to that box's CSS content, and set it to span an absurdly high number.

    .container {
      display: grid;
      grid-template-columns: repeat(3, minmax(10rem, 1fr)) [last-col] 35%;
      grid-template-rows: auto [last-line];
    }
    
    .box {
      background-color: blue;
      padding: 20px;
      border: 1px solid red;
    }
    
    .box:nth-child(3) {
      background-color: yellow;
      grid-column: last-col / span 1;
      grid-row: 1 / last-line;
      grid-row-start: span 9000;
    }
    <div class="container">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box">3</div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>

    This is a non-optimal solution and does not work in every browser, so be careful! Although this may appear to work in some browsers (Chrome), other browsers (Firefox) will create the absurd number of rows which causes problems.