Back to Playground
CSS

CSS Grid Masonry Layout

Pinterest-style masonry layout using modern CSS Grid with dynamic item heights.

CSSGridResponsive

CSS Grid Masonry Layout

Pinterest-style masonry layout using modern CSS Grid with dynamic item heights. No JavaScript calculations needed for positioning!

CSS GRID

Pure CSS

No JS positioning

RESPONSIVE

Auto

Adapts to screen size

DYNAMIC

Any Size

Variable heights

Basic Masonry Grid

Simple masonry layout with fixed column count and variable item heights.

150px
200px
180px
220px
160px
190px

Responsive Columns

Adjust the number of columns dynamically. Layout automatically recalculates.

#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#11
#12

Image Gallery

Pinterest-style image gallery with hover effects and dynamic content.

Nature

Mountain Vista

200px

Urban

City Lights

300px

Nature

Ocean Waves

250px

Nature

Forest Path

180px

Landscape

Desert Dunes

320px

Sky

Sunset Sky

220px

Sky

Northern Lights

280px

Nature

Tropical Beach

190px

Nature

Autumn Leaves

260px

Landscape

Ice Cave

240px

Nature

Lavender Field

210px

Nature

Cherry Blossoms

290px

How It Works

1

Set Grid Auto Rows

Use small row height (e.g., 10px) to create fine-grained grid

grid-auto-rows: 10px
2

Calculate Row Span

Divide item height by row height to get number of rows to span

rowSpan = Math.ceil(height / 10)
3

Apply Grid Row End

Set grid-row-end to span the calculated number of rows

grid-row-end: span {rowSpan}
4

Grid Auto-Placement

CSS Grid automatically positions items to fill gaps efficiently

CSS Code

.masonry-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 10px;
  gap: 16px;
}

.masonry-item {
  grid-row-end: span var(--row-span);
}

/* Calculate row span with JavaScript */
const rowSpan = Math.ceil(
  (itemHeight + gap) / (rowHeight + gap)
);
item.style.setProperty('--row-span', rowSpan);

Perfect For

✓ Image Galleries

Pinterest-style photo layouts

✓ Blog Cards

Article previews with varying content

✓ Product Grids

E-commerce product displays

✓ Portfolio Layouts

Showcase work with dynamic sizing

Code

.masonry-grid {
  display: grid;
  grid-template-columns: repeat(
    auto-fill, 
    minmax(250px, 1fr)
  );
  grid-auto-rows: 10px;
  gap: 16px;
}

.masonry-item {
  grid-row-end: span var(--row-span);
}

/* Calculate row span based on content height */
const item = document.querySelector('.masonry-item')
const rowHeight = 10
const rowGap = 16
const rowSpan = Math.ceil(
  (item.offsetHeight + rowGap) / (rowHeight + rowGap)
)
item.style.setProperty('--row-span', rowSpan)