Auto-Flowing Dense Layouts
You'll learn how to automatically fill gaps in your grid layout by letting smaller items move up into available spaces.
The Problem with Regular Auto-Placement
By default, when CSS Grid auto-places items, it flows them in order—left to right, top to bottom. If a large item can't fit in the current position, Grid leaves a gap and moves to the next row. This can create awkward empty spaces, especially when mixing different-sized grid items.
The Dense Keyword Solution
The grid-auto-flow: dense property tells Grid to backfill those gaps. When Grid encounters a smaller item that could fit into an earlier empty space, it places it there instead of following strict document order.
Think of it like Tetris: instead of pieces always falling in order from top to bottom, smaller pieces slide up to fill gaps wherever they fit.
How to Use It
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
grid-auto-flow: dense; /* Enable gap-filling */
}
.item-large {
grid-column: span 2; /* Takes up 2 columns */
}
With dense, if a two-column item creates a gap, a single-column item later in the HTML can move up to fill that space, creating a more compact, visually pleasing layout.
Important Trade-Off
Dense packing reorders items visually but not in the HTML. This can confuse keyboard navigation and screen readers, since the visual order won't match the tab order. Use it primarily for decorative layouts like image galleries, not for forms or interactive content.
Key Takeaway: Use grid-auto-flow: dense to automatically fill empty grid spaces with smaller items, creating compact layouts—but remember it changes visual order, not accessibility order.