CSS

Pure CSS Grid Masonry Layout with `grid-auto-rows`

Implement a responsive, masonry-style layout using CSS Grid's `grid-auto-rows` and `grid-row-end` for dynamic item placement and variable heights without JavaScript.

.masonry-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-gap: 15px;
  grid-auto-rows: 10px; /* Base row height for item spanning */
}

.grid-item {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 5px;
}

/* Example item heights, dynamic */
.grid-item:nth-child(even) {
  grid-row-end: span 25; /* Spans 25 * 10px = 250px */
}

.grid-item:nth-child(odd) {
  grid-row-end: span 35; /* Spans 35 * 10px = 350px */
}
How it works: This technique creates a masonry-like layout purely with CSS Grid. The `masonry-grid` container uses `grid-auto-rows: 10px` to establish small, implicit row tracks. Each `.grid-item` then spans a number of these tracks using `grid-row-end: span X`, where 'X' is the desired height in units of `grid-auto-rows`. This allows items of varying heights to fit compactly into the grid columns without gaps, similar to traditional masonry layouts, and automatically adjusts with column changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs