# Filling the Space in the Last Row with Flexbox

Source

Chris Albrecht posted a question on StackOverflow about grids. Essentially: imagine you have an element with an unknown number of children. Each of those children is some percentage of the width of parent such that they make equal rows, like 25% wide each for four columns, 33.33% wide each for three columns, etc. The goal is to fill the space of this "grid" evenly. There are an unknown number of children, so let's say you were going with 25% and there were 7 children, that would be 4 in the first row and 3 in the second. Chris needed the final 3 to adjust in width to fill the space, rather than leaving the gap.

Flexbox has just the answer for this, which would otherwise likely need to be a JavaScript intervention.

The solution is essentially making the children able to wrap with flex-wrap, and then filling the space with flex-grow.

.grid {
display: flex;
flex-wrap: wrap;
}

.grid-item {
flex-grow: 1;
min-width: 25%;
}


Here's a visual example of that when each grid item is red and separated with a border:

By adjusting the min-width at different @media query breakpoints, you can make it responsive pretty easily:

.grid-item {
flex-grow: 1;
min-width: 25%;
}
@media (max-width: 1200px) {
.grid-item {
min-width: 33.33%;
}
}


The demo:

See the Pen Wrapping Flexbox with Media Query Widths by Chris Coyier (@chriscoyier) on CodePen.