Dense Auto-Placement
You'll learn how to fill visual gaps in your grid by using the dense keyword with grid-auto-flow.
The Problem: Awkward Gaps
When you explicitly place some grid items using grid-column or grid-row, the auto-placement algorithm places remaining items in order, often leaving empty cells where items don't fit. Imagine packing boxes on shelves—if you've already placed a few large boxes in specific spots, smaller boxes that come later might leave gaps behind them as they move forward looking for space.
The Solution: Dense Packing
The dense keyword tells the grid to actively backfill those gaps. Instead of only moving forward through the grid, the algorithm looks backward to fill any holes with items that fit.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: dense; /* Fill gaps! */
}
You can also combine dense with direction:
grid-auto-flow: row dense; /* Row direction, dense packing */
grid-auto-flow: column dense; /* Column direction, dense packing */
When to Use It
Dense packing is perfect for image galleries, masonry-style layouts, or dashboards where visual compactness matters more than source order. However, important warning: dense packing changes the visual order of items, which can confuse keyboard and screen reader users. Only use it when the order isn't semantically important.
The Trade-Off
Dense packing creates a tighter, more polished visual layout, but it disconnects the visual presentation from your HTML order. The algorithm will move items around to fill gaps, so item #5 in your HTML might appear before item #3 on screen.
Key Takeaway: Use grid-auto-flow: dense to eliminate visual gaps in your grid, but only when the display order doesn't affect accessibility or user understanding.