Search code examples
csscss-grid

CSS grid not considering min value in minmax along with auto-fit


Hi Im trying to create responsive column with the behaviour. The width of the column can go between 335px or 540px.

But when i use grid-template-columns: repeat(auto-fit, minmax(335px, 540px)) it seems only the 540px is taken into consideration.

Like if there is 700px available, i would like 3 items laid out in 2 columns.

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(335px, 540px));
  grid-gap: 10px;
  row-gap: 10px;
}

.item {
  background: red;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="box">
    <div class="item item1">1</div>
    <div class="item item2">2</div>
    <div class="item item3">3</div>
  </div>
</body>
</html>


Solution

  • Consider max-width on your elements instead and use 1fr inside the minmax()

    .box {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(335px, 1fr));
      grid-gap: 10px;
    }
    
    .item {
      background: red;
      max-width: 540px;
    }
    <div class="box">
      <div class="item item1">1</div>
      <div class="item item2">2</div>
      <div class="item item3">3</div>
    </div>