CSS
Efficient Grid Packing with 'grid-auto-flow: dense'
Optimize your CSS Grid layouts to fill empty spaces and achieve a 'masonry-like' effect using the 'grid-auto-flow: dense' property for efficient item packing.
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr); /* Fixed 3 columns for demonstration */
grid-auto-rows: minmax(100px, auto); /* Flexible row height */
grid-auto-flow: dense; /* Instructs grid to try and fill gaps */
gap: 10px; /* Space between grid items */
max-width: 900px;
margin: 0 auto;
border: 1px solid #eee;
padding: 10px;
}
.gallery-item {
background-color: #f4f4f4;
border: 1px solid #ddd;
padding: 15px;
text-align: center;
}
.gallery-item.wide {
grid-column: span 2; /* Item spans two columns */
}
.gallery-item.tall {
grid-row: span 2; /* Item spans two rows */
}
.gallery-item.big {
grid-column: span 2;
grid-row: span 2;
}
How it works: The `grid-auto-flow: dense` property helps fill gaps in a grid layout by allowing items that come later in the source order to appear earlier if they fit into an available empty space. This is particularly useful for gallery or dashboard layouts where items have varying sizes (e.g., spanning multiple columns or rows) and you want to avoid large empty areas, creating a more packed or 'masonry-like' appearance without explicit positioning.