CSS

CSS Grid: Responsive Masonry-like Layout

Achieve a dynamic, masonry-like photo gallery or card layout using CSS Grid's `grid-auto-flow: dense` to minimize empty spaces between items.

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-auto-rows: 10px; /* Base unit for row heights */
  grid-gap: 15px;
  grid-auto-flow: dense; /* Fill gaps efficiently */
}

.gallery-item {
  background-color: #e0e0e0;
  padding: 10px;
  border-radius: 5px;
}

.gallery-item.wide {
  grid-column: span 2;
}

.gallery-item.tall {
  grid-row: span 3; /* Example height based on grid-auto-rows: 10px */
}
How it works: This CSS Grid snippet creates a responsive, masonry-like layout for items of varying sizes. `grid-template-columns: repeat(auto-fill, minmax(200px, 1fr))` creates flexible columns. `grid-auto-rows: 10px` sets a base row height, allowing items to span multiple rows (e.g., `grid-row: span 3` for a 'tall' item means it takes 3 * 10px height). Crucially, `grid-auto-flow: dense` enables the grid to fill empty spaces more efficiently by reordering items, helping to create the visual appeal of a masonry layout.

Need help integrating this into your project?

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

Hire DigitalCodeLabs