When you place items in a grid, you can manually specify where each one goes. But what about
items you do not explicitly place? That is where grid-auto-flow comes in. It
controls how the browser automatically places items that you have not assigned a position to.
Row vs Column
The default value is row, which means auto-placed items fill across rows first,
then move to the next row. If you set it to column, items fill down columns first,
then move to the next column.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: row;
}
With grid-auto-flow: row, items flow left to right, then wrap to the next row.
With column, they flow top to bottom, then wrap to the next column.
The dense Keyword
You can add dense to the auto-flow value: grid-auto-flow: row dense.
This tells the grid to try to fill in any gaps left by larger items. Without dense, if you
have a large item that spans two columns, the next item will skip that space. With dense,
the browser backtracks and fills the gap.
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-flow: row dense;
}
.large-item {
grid-column: span 2;
}
Be careful with dense though — it can reorder your items visually, which might cause accessibility issues if the visual order does not match the DOM order.
Practical Use
Auto-flow is most useful when you have a mix of explicitly placed items and auto-placed ones.
For example, in a gallery layout you might pin a featured image to a specific spot and let the
rest fill in around it. The dense packing ensures no awkward gaps appear.