How to make the items in the last row consume remaining space in CSS Grid?
Solution 1:
This is totally possible with CSS grid by combining the CSS rules nth-child and nth-last-of-type. The only caveat is that the number of columns needs to be known in advance.
.grid {
display: grid;
grid-template-columns: auto auto auto;
justify-items: start;
grid-gap: 10px;
}
.grid div {
border: 1px solid #ccc;
width: 100%;
}
.grid > *:nth-child(3n-1) {
justify-self: center;
text-align: center;
}
.grid > *:nth-child(3n) {
justify-self: end;
text-align: right;
}
.grid > *:nth-child(3n-1):nth-last-of-type(1) {
border-color: red;
grid-column: span 2;
}
.grid > *:nth-child(3n-2):nth-last-of-type(1) {
border-color: red;
grid-column: span 3;
}
<div class="grid">
<div>text</div>
<div>TEXT</div>
<div>text</div>
<div>text</div>
<div>TEXT</div>
<div>text</div>
<div>text</div>
<div>TEXT</div>
</div>
Solution 2:
I don't think CSS Grid is the best option for the layout you're trying to build, at least not if it's going to be dynamic and you don't really know how many items will be on the container all the time. Flexbox is actually better for one-dimensional layouts; it might be a little harder to keep everything the exact same size and using all of the available space exactly as you need it, but at the end this type of cases is what Flexbox is built for.
And of course you can make use of 100% width by using few calculations on CSS as well.
CSS Grid might be better to keep rows AND columns aligned, but this is a different case.
.container {
display: flex;
flex-wrap: wrap;
box-sizing: border-box;
}
.flex-item {
width: 30%;
border: 1px solid #000;
flex-grow: 1;
min-height: 120px;
box-sizing: border-box;
margin: 0 5px 10px;
justify-content: space-between;
text-align: center;
}
<div class="container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
<div class="flex-item">4</div>
<div class="flex-item">5</div>
<div class="flex-item">6</div>
<div class="flex-item">7</div>
</div>