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>
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With