Search code examples
csscss-grid

CSS Grid: Trouble getting autofit to work


The below code properly places the 2 rectangular divs on one row when I repeat 2 of the minmax value. It breaks when I instead repeat an autofit or autofill.

Working example: https://codepen.io/seandez/pen/mddLwNp

<div id="outerContainer">
  <div class="longRectangle"></div>
  <div class="longRectangle"></div>
</div>

// css
body { background-color: black; }

.longRectangle {
  border: 2px dashed white;
  height: 100px;
  width: 400px;
}

#outerContainer {
  display: grid;
  border: 2px solid green;
  grid-template-columns: repeat(autofit, minmax(200px, 1fr));
}

I have the screen width for 2 rows between 200px and a full frame to fit on 1 row. Why is it defaulting to 2 rows and what is the correct adjustment?

The intent here is to get an example working that will simulate wrapping 2 elements into a vertical stack at small screen widths. The default should be 2 columns.


Solution

  • its auto-fit not autofit. You also don't need to set width on .longRectangle because that will be controlled by grid.

    body { background-color: black; }
    
    .longRectangle {
      border: 2px dashed white;
      height: 100px;
    }
    
    #outerContainer {
      display: grid;
      border: 2px solid green;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }
    <div id="outerContainer">
        <div class="longRectangle"></div>
        <div class="longRectangle"></div>
    </div>