How to make the items in the last row consume remaining space in CSS Grid?

Bondsmith picture Bondsmith · Jan 25, 2019 · Viewed 7.3k times · Source

Is there a way to force all the items in the last row, of a grid, to fill the row, no matter how many they are?

I do not know the number of items that will be in the grid so I cannot target them directly. I tried to use grid-auto-flow: dense, but it is not really helping.

This is my question visualized: enter image description here:

Answer

IvanS95 picture IvanS95 · Jan 25, 2019

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>