Search code examples
csscss-gridgrid-layout

Why do CSS Grid items not wrap if container has no defined height?


I have a list of items in a grid layout and the grid container has a width set, but no height set.

I want the items to populate columns until it hits the container width, then wrap into rows.

But right now I can only get it to work that way if define a height on the container.

Below is a snippet.

The grid items never wrap unless you uncomment the height rule for the container, but I want the container grow/shrink to fit after the grid wraps.

.box {
  height: 150px;
  width: 150px;
  background-color: red;
}

.container {
  width: 500px;
  /*   height: 500px; */
  background-color: blue;
  display: grid;
  grid-auto-flow: column;
  grid-gap: 5px;
  grid-template-rows: repeat(auto-fill, minmax(150px, 1fr));
}
<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 class="box"></div>
</div>


Solution

  • I want the items to populate columns until it hits the container width, then wrap into rows.

    Then why are you using grid-auto-flow: column and grid-template-rows?

    With grid-auto-flow: column the grid items will flow vertically, filling rows then creating new columns. You're saying you want the reverse: fill columns, then create new rows. So stick with the default, grid-auto-flow: row.

    Along the same lines, switch from grid-template-rows to grid-template columns. You want to auto fill columns, not rows.

    No height is necessary on the grid container.

    In fact, you don't need a width or height on the items either.

    .container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
      grid-auto-rows: 150px;
      grid-gap: 5px;
      width: 500px;
      background-color: blue;
    }
    
    .box {
      background-color: red;
    }
    <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 class="box"></div>
    </div>

    More details: Make grid container fill columns not rows