Search code examples
csscss-grid

How to specify different size for each grid element and maintain wrapping?


Problem:

Right now both of the grid elements below are min: 250px, max: 1fr in size. They wrap on screen size <250px

I'm trying to achieve the following:

  • the first element to be min: 250px, max: 2fr
  • the second element to be min: 250px, max: 1fr

but also maintain wrapping to 1fr each on screen size <250px (the way they wrap now basically)

Code:

Codepen: https://codepen.io/anon/pen/dEBQgm?editors=1100

<div class="container">
  <div class="child">Child 1</div>
  <div class="child">Child 2</div>
</div>

...

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  grid-gap: 16px;
}

.child {
  background: #aaa;
  height: 32px
}

I tried this but I lost the wrapping:

grid-template-columns: minmax(250px, 2fr) minmax(250px, 1fr);

Solution

  • You can try flexbox for this:

    .container {
      display: flex;
      flex-wrap: wrap;
      margin:-8px; /*Pay attention to this! You may need overflow:hidden on a parent container*/
    }
    
    .child {
      background: #aaa;
      height: 32px;
      min-width: 250px;
      flex-basis: 0%;
      margin: 8px;
    }
    
    .container> :first-child {
      flex-grow: 2;
    }
    
    .container> :last-child {
      flex-grow: 1;
    }
    
    .container-grid {
      display: grid;
      grid-template-columns: minmax(250px, 2fr) minmax(250px, 1fr);
      grid-gap:16px;
    }
    .container-grid > .child {
      margin:0;
    }
    flexbox with wrapping
    <div class="container">
      <div class="child">Child 1</div>
      <div class="child">Child 2</div>
    </div>
    grid without wrapping:
    <div class="container-grid">
      <div class="child">Child 1</div>
      <div class="child">Child 2</div>
    </div>