Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make CSS Grid items take up remaining space?

I have a card built with CSS Grid layout. There might be an image to the left, some text to the right top and maybe a button or a link at the right bottom.

In the code below, how can I make the green area take up as much space as possible and at the same time make the blue area take up as little space as possible?

The green should push the blue area down as far as possible.

https://jsfiddle.net/9nxpvs5m/

.grid {    display: grid;    grid-template-columns: 1fr 3fr;    grid-template-areas:      "one two"      "one three"  }    .one {    background: red;    grid-area: one;    padding: 50px 0;  }    .two {    background: green;    grid-area: two;  }    .three {    background: blue;    grid-area: three;  }
<div class="grid">    <div class="one">      One    </div>    <div class="two">      Two    </div>    <div class="three">      Three    </div>  </div>
like image 451
Jens Törnell Avatar asked Aug 21 '17 14:08

Jens Törnell


People also ask

Why are there gaps in my grid CSS?

The vertical gaps are caused by the images not filling the vertical space in the grid items. The problem is made worse with align-items: center on the container, which removes the align-items: stretch default. Essentially, there are no gaps between grid items.

What is auto fill in CSS Grid?

Auto-fill: The auto-fill property fills the rows with as many columns as it can fit. The newly added column may be empty but it will still occupy a space in the given row. It is an important property in the CSS grid that make a responsive layout without writing a media query for each grid.

How do I fix the size of the grid?

By default, a grid item cannot be smaller than the size of its content. Grid items have an initial size of min-width: auto and min-height: auto . You can override this behavior by setting grid items to min-width: 0 , min-height: 0 or overflow with any value other than visible .


1 Answers

Adding grid-template-rows: 1fr min-content; to your .grid will get you exactly what you're after :).

.grid {    display: grid;    grid-template-columns: 1fr 3fr;    grid-template-rows: 1fr min-content;    grid-template-areas:      "one two"      "one three"  }    .one {    background: red;    grid-area: one;    padding: 50px 0;  }    .two {    background: green;    grid-area: two;  }    .three {    background: blue;    grid-area: three;  }
<div class="grid">    <div class="one">      One    </div>    <div class="two">      Two    </div>    <div class="three">      Three    </div>  </div>

Jens edits: For better browser support this can be used instead: grid-template-rows: 1fr auto;, at least in this exact case.

like image 181
Kevin Powell Avatar answered Oct 11 '22 23:10

Kevin Powell