Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get items to stretch to fill width?

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 100px);
  grid-gap: 3px;
  border: 1px solid green;
}

.item {
  border: 1px solid red;
  height: 50px;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

How can I stretch the red item boxes a little bit so that they fill the entire width of the green container box?

They should all be the same width, and a little bit bigger than 100px.

The last row should be left-aligned as it is now.

like image 790
mpen Avatar asked Dec 19 '17 23:12

mpen


1 Answers

You just need to add a fraction unit to the grid-template-columns rule.

grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));

This rule creates as many columns as will fit in the container.

The minimum width of each column is 100px.

The maximum width is 1fr, which means the column will consume any free space on the row.

Now all horizontal space in the container is being used.

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  grid-auto-rows: 50px;
  grid-gap: 3px;
  border: 1px solid green;
}

.item {
  border: 1px solid red;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

These posts explain the solution above in more detail:

  • Equal width flex items even after they wrap
  • The difference between percentage and fr units in CSS Grid Layout
like image 157
Michael Benjamin Avatar answered Sep 18 '22 06:09

Michael Benjamin