π What is grid-auto-flow?
grid-auto-flow is a CSS Grid container property that controlshow grid items are automatically placed when you do NOT explicitly specifygrid-row or grid-column for them.
It determines the **direction** and **behavior** of the auto-placement algorithm β helping you build flexible layouts without specifying exact positions for every item.
π― Why is grid-auto-flow important?
- Creates automatic layouts without specifying positions
- Defines the direction items should flow (row-wise or column-wise)
- Enables Masonry-like layouts with dense
- Useful for dynamic content like galleries, cards, dashboards
π Available Values
| Value | Description |
|---|---|
| row (default) | Places items left-to-right, then top-to-bottom |
| column | Places items top-to-bottom, then left-to-right |
| dense | Back-fills gaps to create tighter layouts |
| row dense | Row flow + gap filling |
| column dense | Column flow + gap filling |
π§ͺ Basic Example
Default Behavior (row)
.container {
display: grid;
grid-template-columns: repeat(3, 150px);
grid-auto-flow: row; /* default */
}Items fill left to right, then move to the next row.
π Example: Column Flow
column Flow Example
.container {
display: grid;
grid-template-rows: repeat(3, 150px);
grid-auto-flow: column;
}Items fill vertically first, then move to the next column.

π₯ Using dense for Masonry-like Layouts
The dense keyword lets the grid back-fill empty gaps by placing later items into spaces left by larger items.
Masonry-Like Grid
.container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-flow: row dense;
}
.large {
grid-column: span 2;
}Note
π§© Real-World Use Case Example
Auto Placed Product Grid
.products {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-auto-flow: row dense;
gap: 20px;
}
.product.featured {
grid-column: span 2;
grid-row: span 2;
}Featured products become larger, and the dense flow fills in gaps beautifully.
π± Responsive Example
Responsive grid-auto-flow
.gallery {
grid-auto-flow: row;
}
@media (min-width: 800px) {
.gallery {
grid-auto-flow: row dense;
}
}On small screens: normal flow
On larger screens: dense layout for optimized gaps
β οΈ Common Mistakes
- Expecting dense to always preserve item order (it won't)
- Using column without understanding it fills vertically first
- Not defining rows or columns β causing unexpected layout
- Trying to use grid-auto-flow on grid items (it only works on the container!)
Note
β’ grid-template-columns
β’ grid-template-rows
π₯ Summary
grid-auto-flow controls how the browser automatically places grid items when explicit placement is not provided. It influences the direction (row/column) and the packing strategy (dense).
Learn more βMDN Docs π