CSS Grid: grid-auto-flow

By default items that spill outside of the defined grid tracks will appear in new, auto-generated rows. That is, unless we set grid-auto-flow to column.

grid-auto-flow defaults to row and take the value of column. It’s defined on the grid container.

Compare these two examples, where the items are placed implicitly. First with the default value of row for grid-auto-flow:

.container {
  display: grid;

  grid-template-rows: 1fr;
  grid-template-columns: auto;
  grid-auto-flow: row;
}
Item 1
Item 2
Item 3

Then with column:

.container {
  display: grid;

  grid-template-rows: 1fr;
  grid-template-columns: auto;
  grid-auto-flow: row;
}
Item 1
Item 2
Item 3

And in this 3rd example, item-1 and item-2 are place explicitly, but item-3 is still auto-placed into a new column instead of a new row:

.container {
  display: grid;

  grid-template-rows: 1fr;
  grid-template-columns: auto;
  grid-auto-flow: column;
}

.item-1 {
  grid-row: 1;
  grid-column: 1;
}

.item-2 {
  grid-row: 2;
  grid-column: 1;
}
Item 1
Item 2
Item 3

The Dense Keyword

By default, if gaps are created in the grid when placing items, auto-positioned grid items will not fill the gaps, but instead will be added after the last item. We can change that with the dense keyword, which tells the implicit grid algorithm to try and go back and fill the gaps with the auto-placed items, changing the order of items when needed:

.container {
  display: grid;
  grid-gap: 1rem;

  grid-auto-flow: column dense;
}

Or:

.container {
  display: grid;
  grid-gap: 1rem;

  grid-auto-flow: row dense;
}

This can be really useful when creating image galleries where the order of items doesn’t matter as much.

See also

✖ Clear

🕵 Search Results

🔎 Searching...