Search code examples
cssgrid

grid-template-columns that shrink and grow between a maximum and minimum pixel size


I want grid columns that are a minimum of 200px and a maximum of 300px. I'm trying this, but the columns are always 300px.

grid-template-columns: repeat(auto-fit, minmax(200px, 300px));

I can make columns that shrink like this:

grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

But then they get too big.

I've checked the docs for minmax() and don't see an applicable example.

Is there a workaround for this?

See The Fiddle

The Answer

Important elements to the answer include changing to: minmax(300px, auto)); as well as adding box-sizing: border-box;

Without those, the grid is not centered when it's down to one column.

Thanks!


Solution

  • You may use minmax(200px,1fr)or minmax(200px,auto) and then max-width on the children themselves to avoid them grow bigger than 300px.

    possible examples

    * {
      box-sizing: border-box
    }
    
    body {
      padding: 20px;
      font-family: Helvetica;
    }
    /* sizing */
    .wrapper {
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }
    .wrapper.bis {
      grid-template-columns: repeat(auto-fit, minmax(200px, auto));
    }
    
    .box {
      max-width: 300px
    }
    /* --- */
    .wrapper {
      display: grid;
      grid-gap: 10px;
    }
    
    .box {
      background-color: #20262e;
      color: #fff;
      border-radius: 3px;
      padding: 20px;
      font-size: 14px;
      max-width: 300px
    }
    
    .box {
      /* Demo see average width by chunks of 50px bg-gradient-color */
      background-image: repeating-linear-gradient(to right, red 0 50px, green 50px 100px);
      background-position: 0 0;
      background-repeat: repeat-x;
      background-size: auto 5px;
    }
    <div class="wrapper">
      <div class="box a">A - 200px,1FR</div>
      <div class="box b">B</div>
      <div class="box c">C</div>
      <div class="box d">D</div>
      <div class="box e">E</div>
      <div class="box f">F</div>
    </div>
    <hr>
    <div class="wrapper bis">
      <div class="box a">A - 200px,AUTO</div>
      <div class="box b">B</div>
      <div class="box c">C</div>
      <div class="box d">D</div>
      <div class="box e">E</div>
      <div class="box f">F</div>
    </div>