I am trying to make the CSS grid automatically size the final set of elements such that they autofill the last row if the amount of entries does not match the column count.
Let the number of column we want be c. By observation we know that there are c columns (by definition), c - 1 gaps and 2 paddings, which sum up to 100% of the container’s width:
Overall this is not a task for CSS-Grid but Flexbox. In Flexbox you can make use of flex-grow: 1 to make the elements grow to fill the remaining space.
Flexbox can make use of flex-wrap: wrap so that elements that would overflow would break to the next row. The tricky part here is, that as such the width of every call must be calculated correctly.
For the calculations, I recommend the usage of CSS variables. One variable for the gaps and then one variable for the columns. The correct width can be calculated by using that algorithm:
width = ((100% - (size of gaps * (amount of columns - 1))) / amount of columns)
To work correctly the containers box-model should be set to default (content-box) while the cards box model must be set to border-box so that the padding and border are included in the width:
3
Answers
You can do so by selecting the last odd child and providing
grid-column: 1 / -1
.You need
display: flex
and a bit of math.First, create a container element and its items:
Then, make it a flexbox with
flex-wrap: wrap
:Let the number of column we want be
c
. By observation we know that there arec
columns (by definition),c - 1
gaps and 2 paddings, which sum up to100%
of the container’s width:This means an item’s width can be calculated as:
We translate that to CSS accordingly, and add
flex-grow: 1
to make the last items take all remaining spaces:Try it:
Overall this is not a task for CSS-Grid but Flexbox. In Flexbox you can make use of
flex-grow: 1
to make the elements grow to fill the remaining space.Flexbox can make use of
flex-wrap: wrap
so that elements that would overflow would break to the next row. The tricky part here is, that as such the width of every call must be calculated correctly.For the calculations, I recommend the usage of CSS variables. One variable for the gaps and then one variable for the columns. The correct width can be calculated by using that algorithm:
width = ((100% - (size of gaps * (amount of columns - 1))) / amount of columns)
To work correctly the containers box-model should be set to default (
content-box
) while the cards box model must be set toborder-box
so that the padding and border are included in the width: