9

I have a css grid and it looks and works great when there are many items. However, when there are 1, 2 or 3 items the cards are stretched.

I tried to set the max-width to each card but the width of the columns remain the same. Is there a way to set max-width of each column? I need to use it only when there are 3 columns or less. (I am very new to css grid)

.big-container {
  padding: 0 10%;
}

.header {
  width: 100%;
  height: 50px;
  background-color: blue;
}
.container {
  border: 1px solid black;
  display: grid;
  justify-content: space-between;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 10px;
}
.box {
  border: 1px solid black;
  height: 30px;
  background-color: yellow;
}
<div class="big-container">
  <div class="header"></div>
  <p>Text</p>
  <div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>

</div>
</div>

Thanks!

Tom Bom
  • 1,589
  • 4
  • 15
  • 38
  • Try setting minmax in pixel values, like `minmax(100px, 200px)`. This means that the grid columns can be maximum 200px wide. – Sujan Sundareswaran Mar 03 '18 at 07:57
  • Thanks, I've just tried it but it puts a big gap between the boxes when there are many of them. – Tom Bom Mar 03 '18 at 08:02
  • Do you want 4 columns in one row? why not just define it like that? It looks like your container is responsive and your columns are made to fit inside of that grid no matter the amount of divs – Gabby_987 Mar 03 '18 at 09:06

1 Answers1

17

Setting grid-template-columns to auto-fill, will prevent cells to stretch in case of column < 4

see below snippet:

.big-container {
  padding: 0 10%;
}

.header {
  width: 100%;
  height: 50px;
  background-color: blue;
}

.container {
  border: 1px solid black;
  display: grid;
  justify-content: space-between;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  grid-gap: 10px;
}

.box {
  border: 1px solid black;
  height: 30px;
  background-color: yellow;
}
<div class="big-container">
  <div class="header"></div>
  <p>Text</p>
  <div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>
Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52