Grid Auto-Flow: row, column, and dense
You'll learn how to control the direction Grid items fill into the grid and how to eliminate empty gaps automatically.
When you place items in a Grid without specifying exact positions, CSS has to decide where they go. The grid-auto-flow property controls which direction the automatic placement algorithm flows, and whether it tries to pack items tightly to fill gaps.
The Three Main Values
grid-auto-flow: row (default)
Items fill left-to-right across rows, then move down to the next row when one is full. Think of reading a book—left to right, top to bottom.
grid-auto-flow: column
Items fill top-to-bottom down columns, then move to the next column when one is full. Think of reading a Japanese manga—top to bottom, right to left.
grid-auto-flow: dense
This is a modifier you add to row or column (e.g., row dense). When enabled, Grid uses a "backfilling" algorithm: if a smaller item can fit into an earlier gap left by a larger item, it jumps back to fill that space, creating a tighter layout. Without dense, items only move forward, leaving gaps behind.
When to Use Dense
Use dense when visual order doesn't matter (like image galleries) and you want zero white space. Avoid it when the visual order needs to match the HTML order for accessibility—screen readers follow the DOM, not visual placement.
Example Syntax
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: row dense; /* Fill rows, backfill gaps */
}
Key Takeaway: grid-auto-flow controls whether auto-placed items fill by row or column, and dense enables gap-filling at the cost of visual reordering.