CSS
Efficiently Packing Grid Items with `grid-auto-flow: dense`
Optimize the arrangement of grid items by filling available empty spaces, creating a more compact and visually appealing layout for items of varying sizes.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal width columns */
grid-auto-rows: minmax(100px, auto); /* Minimum row height, auto for content */
grid-auto-flow: dense; /* Allows smaller items to fill gaps left by larger items */
gap: 15px;
width: 90%;
margin: 20px auto;
border: 1px solid #000;
}
.grid-item {
background-color: #e0e0ff;
padding: 15px;
border: 1px solid #a0a0ff;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
}
.item-wide {
grid-column: span 2; /* Item spans 2 columns */
}
.item-tall {
grid-row: span 2; /* Item spans 2 rows */
}
How it works: The `grid-auto-flow: dense` property optimizes the placement of implicitly-placed grid items by allowing the algorithm to 'backtrack' and fill empty spaces left by larger items. Without `dense`, items are placed strictly in order, which can leave large gaps if a wide or tall item cannot fit immediately. Combined with `grid-auto-rows` for flexible row sizing, `dense` helps create more compact and visually appealing layouts, especially useful for card-based designs where content heights or widths vary.