How to define the last row of a css grid explicitly using grid-template-rows or grid-auto-rows?

Viewed 96

We can explicitly define the first row, or the first 2 rows, or the first n rows explicitly using grid-template-rows: 1fr 2fr ... 1fr. We can also define alternating implicit rows using grid-auto-rows by grid-auto-rows: 1fr 2fr

Is it possible to define the last row using grid-template-rows or grid-auto-rows? And in a more general sense is it possible to define an nth row only using the above?

In the example below I have set the size of all implicit rows to be the size of the maximum row in the grid.

Now, I wish to select the last row (the one with the button) and set its height to auto so that its height is equal to the height of the button inside.

.grid { 
  display: grid;
  grid-template-columns: 1fr;
  grid-auto-rows: 1fr;
}

.grid > div { 
  border: 1px solid green;
  width: 300px;
  min-height: 50px;
}
<div class="grid">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet in omnis molestias suscipit animi qui, sunt asperiores beatae autem maxime hic, excepturi nostrum, pariatur ratione accusamus alias corporis. Voluptate, aliquid.</div>
  <div></div>
  <div></div>
  <div></div>
  <div>
    <button>
      I wish my row was the same height as me :(
    </button>
  </div>
  
</div>

1 Answers

You can try using fit-content for the last row.

<style>
    .grid {
      display: grid;
      grid-template-columns: 1fr;
      grid-auto-rows: minmax(50px,1fr);
    }

    .grid > div {
      border: 1px solid green;
      width: 300px;
    }
    .grid > div:not(.footer) {
      min-height: 50px; /*this is just for codepen preview, should work in browser without it*/
    }
    .footer{
        height: fit-content;
    }
</style>
<div class="grid">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet in omnis molestias suscipit animi qui, sunt asperiores beatae autem maxime hic, excepturi nostrum, pariatur ratione accusamus alias corporis. Voluptate, aliquid.</div>
    <div></div>
    <div></div>
    <div></div>
    <div class="footer">
        <button>
            I wish my row was the same height as me :(
        </button>
    </div>
</div>

Related