π What is grid-auto-flow: dense?
grid-auto-flow: dense is an advanced CSS Grid placement mode that tells the grid toback-fill empty gaps left by larger or explicitly positioned items. This creates a tighter, more compact layout β similar to a masonry grid effect.
π Why Use dense?
- To eliminate leftover empty spaces in the grid
- To create a compact, masonry-like layout
- To visually optimize unpredictable/dynamic content
- To improve layout density without manually positioning items
Note
π― Syntax
Basic Syntax
grid-auto-flow: row dense;
/* or */
grid-auto-flow: column dense;π§ͺ Basic Example β Row Dense
Simple dense Grid
.container {
display: grid;
grid-template-columns: repeat(4, 150px);
gap: 10px;
grid-auto-flow: row dense;
}
.item.large {
grid-column: span 2;
grid-row: span 2;
}Items with larger spans may create gaps β dense fills them efficiently.

π How dense Works Internally
Without dense:
- Grid fills items in source order
- If a big item creates a gap, it stays empty
With dense:
- The algorithm scans backward
- Later items can be placed into earlier empty cells
- Creates compact, tightly packed layouts
π₯ Visual Comparison
| Mode | Behavior |
|---|---|
| grid-auto-flow: row | Gaps remain unfilled |
| grid-auto-flow: row dense | Gaps are filled using later items |
π§© Masonry-Style Example
Masonry-like Using dense
.gallery {
display: grid;
gap: 15px;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-auto-flow: dense;
}
.gallery .tall {
grid-row: span 2;
}
.gallery .wide {
grid-column: span 2;
}By mixing row and column spans and enabling dense, you can create highly flexible masonry-style layouts without JS.
π± Responsive Example
Responsive dense Layout
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
grid-auto-flow: row;
}
@media (min-width: 768px) {
.cards {
grid-auto-flow: row dense;
}
}Dense packing happens only on larger screens where it looks visually balanced.
β οΈ Common Mistakes
- Expecting dense to preserve item order (it wonβt)
- Using dense without defining track sizes β unpredictable layout
- Using dense for content that must follow strict reading order
- Not testing accessibility when DOM order matters
Note
π§ When NOT to Use dense
- Forms, reading content, chat messages, or any logical sequence
- Content that depends heavily on user order
- Screen readers reading items in DOM order
π₯ Summary
grid-auto-flow: dense is perfect for advanced grid layouts where visual compactness is prioritized. It intelligently fills gaps, enhances layout density, and supports masonry-style designs without extra JavaScript.
Learn more βMDN Docs π