Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set max-width of css grid columns [duplicate]

Tags:

html

css

css-grid

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!

like image 883
Tom Bomb Avatar asked Mar 03 '18 07:03

Tom Bomb


1 Answers

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>
like image 194
Spring Avatar answered Sep 22 '22 07:09

Spring