Auto-Placement Algorithm
You'll learn: How the CSS Grid automatically decides where to place items when you don't explicitly position them.
When you create a grid and add items without specifying grid-column, grid-row, or grid-area, the browser doesn't just randomly scatter them—it follows a predictable auto-placement algorithm to determine where each item goes.
How the Algorithm Works
Think of the auto-placement algorithm like an organized librarian shelving books: it moves systematically through the grid, placing each item in the next available cell according to specific rules.
The algorithm follows this logic:
- Processes items in DOM order (unless you've used
order) - Checks the current grid position (starting at row 1, column 1)
- Places the item in the first available cell that fits
- Moves to the next position based on
grid-auto-flow(row-by-row or column-by-column)
For items with explicit placement (like grid-column: 2), the algorithm places those first, then fills in the auto-placed items around them.
The Default Flow
By default, the algorithm fills the grid row by row, left to right—just like reading text. When a row is full, it moves to the next row. This is because the default grid-auto-flow value is row.
If some items span multiple tracks (using span), the algorithm looks for gaps large enough to accommodate them.
Key Takeaway: The auto-placement algorithm places grid items systematically in DOM order, filling available cells row-by-row (by default), while respecting any explicitly positioned items and track-spanning requirements.