← Back to all snippets
CSS

Creating a Responsive Masonry-like Layout with CSS Grid and `grid-auto-flow: dense`

Achieve a Pinterest-style masonry layout using CSS Grid's `grid-auto-flow: dense` and `grid-row-end: span X`, effectively packing items to minimize empty space without JavaScript.

.masonry-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    grid-auto-rows: 10px; /* Base row height for spanning */
    grid-gap: 15px;
    grid-auto-flow: dense; /* Fill in gaps */
}
.grid-item {
    background-color: #e0e0e0;
    padding: 15px;
    border-radius: 5px;
}
/* Example for items taking multiple rows */
.grid-item--height1 { grid-row-end: span 15; } /* Spans 15 * 10px = 150px */
.grid-item--height2 { grid-row-end: span 25; } /* Spans 25 * 10px = 250px */
.grid-item--height3 { grid-row-end: span 35; } /* Spans 35 * 10px = 350px */
How it works: This snippet shows how to create a masonry-like layout with CSS Grid. `grid-template-columns` defines responsive columns. `grid-auto-rows` sets a base row height, and `grid-auto-flow: dense` ensures items pack tightly. By assigning `grid-row-end: span X` to individual items, they can span multiple implicit rows, creating the varied height effect and efficient space utilization without requiring JavaScript for arrangement.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs