Filling the Voids
Sometimes, when you have elements of different sizes (one takes 1 column, another takes 2), empty " holes " can remain in the grid because browser places them strictly in queue order.
Dense Magic
The grid-auto-flow: dense property gives browser the command: " If you encounter an element that doesn't fit, skip it, but come back if you find a small element that fits in the remaining hole " .
.gallery {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-flow: dense; /* Maximum dense element packing */
}
Caution
Using dense can completely mix elements visually. This is great for decorative galleries, but dangerous for forms or lists where logical element order matters.
Tip
This property makes your layout look like " Masonry " layout (like in Pinterest), but without using complex JavaScript libraries.