csscss-gridgrid-layout

Grid-auto-rows with auto - how controlling the height of the last line?


I need to create a grid container with an unknown number of rows - so that all but the last row occupy the height of the content, and the last row (regardless of the height of the content) occupies the remaining height of the grid container.

Here is my HTML variation:

 <div className="grid-container">
      <div className="item">some data 1 </div>
      <div className="item">some data 2</div>
      <div className="item">some data 3</div>
      <div className="item">some data 4</div>
      <div className="last-item">last one</div>
    </div>

I've been trying to do:

.grid-container {
  display: grid;
  grid-template-rows: repeat(auto-fill, min-content) 1fr;
  height: 500px; /* It doesn't really matter, it's just for clarity's sake. */
}
.item {
 height: max-content;
}

grid-template-rows: repeat(auto-fill, min-content) 1fr; - its not valid code (just my attempt to solve the problem), but I don't know how to solve this problem, help please and thanks advance

the last line should stretch to the full height of the container


Solution

  • After trying all the combinations possible with CSS grid, I come to the conclusion that this cannot be achieved with CSS grid.

    We can only achieve this with flexbox and that's why perhaps we say Grids works perfectly in sync with flexbox.

    .grid-container {
          display: flex; 
          flex-direction: column; 
          height: 100vh;
        }
    
        .grid-item {
          flex: 0 1 auto; 
        }
    
        .last-item {
          flex: 1 1 auto; 
          background: orange;
        }
        <div class="grid-container">
          <div class="grid-item">
            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Reiciendis illo quibusdam voluptas
            veritatis? Qui unde totam quas dicta, omnis officiis.
          </div>
          <div class="grid-item">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, impedit.
          </div>
          <div class="grid-item">
            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis, dolore.
          </div>
          <div class="grid-item">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Reprehenderit, ipsa.
          </div>
          <div class="last-item">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus ipsam inventore labore
            mollitia nesciunt rerum maxime rem officia quam ex?
          </div>
          </div>