CSS
Achieve a Masonry-like Layout with CSS Grid
Learn to create a responsive, masonry-style grid layout using CSS Grid's `grid-auto-rows` and `grid-row-end` to handle items of varying heights gracefully, simulating a Pinterest-like appearance.
.masonry-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-rows: minmax(100px, auto); /* Flexible row heights, min 100px */
gap: 15px;
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.grid-item {
background-color: #f9f9f9;
border: 1px solid #e0e0e0;
border-radius: 5px;
padding: 15px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
/* Example classes for different row spans based on content height */
.grid-item.span-2-rows {
grid-row-end: span 2; /* Item spans 2 auto-generated rows */
}
.grid-item.span-3-rows {
grid-row-end: span 3; /* Item spans 3 auto-generated rows */
}
How it works: This snippet demonstrates a method to create a masonry-like layout with CSS Grid. The container uses `grid-template-columns` with `auto-fill` and `minmax` for responsive column management. The key to the masonry effect is `grid-auto-rows: minmax(100px, auto);`, which defines flexible row sizes, and then applying `grid-row-end: span X;` to individual grid items. This tells an item to span a certain number of the auto-generated rows, allowing items of different heights to flow more naturally and fill gaps, mimicking a masonry effect without complex JavaScript calculations.