CSS
CSS Grid Masonry-like Layout for Varying Item Heights
Build a responsive, masonry-like layout using CSS Grid. `grid-auto-flow: dense` efficiently packs items of varying heights, minimizing gaps and optimizing space without JavaScript code.
.masonry-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: 10px; /* Smallest possible row height for granular control */
grid-auto-flow: dense; /* Crucial for filling empty spaces */
gap: 1rem;
}
.grid-item {
background-color: #f0f8ff;
border: 1px solid #add8e6;
padding: 15px;
/* Example: items with varying heights */
}
.grid-item:nth-child(4n+1) { grid-row-end: span 20; } /* Example: tall item */
.grid-item:nth-child(4n+2) { grid-row-end: span 15; }
.grid-item:nth-child(4n+3) { grid-row-end: span 25; }
.grid-item:nth-child(4n) { grid-row-end: span 10; }
How it works: This snippet creates a responsive masonry-like layout using CSS Grid without JavaScript. Key properties include `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))` for flexible columns, and `grid-auto-flow: dense` which allows items to fill any available empty spaces in the grid, rather than maintaining strict order. `grid-auto-rows` with a small unit (e.g., 10px) combined with `grid-row-end: span X` on individual items enables elements of varying heights to span multiple implicit grid rows, mimicking the masonry effect by optimizing vertical space.