Masonry-like Layout with Flexbox

Approximate a masonry layout using Flexbox with column direction and wrapping. Items fill columns top to bottom, creating a Pinterest-style layout.

Advanced Techniques

Detailed Explanation

Masonry-like Layout with Flexbox

True masonry layouts (like Pinterest) are best achieved with CSS Grid's masonry value or JavaScript libraries. However, Flexbox can approximate the effect using flex-direction: column with flex-wrap: wrap.

CSS Code

.masonry {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 800px;
  gap: 16px;
}

.masonry-item {
  flex: 0 0 auto;
  width: calc(33.333% - 11px);
}

How It Works

With flex-direction: column and flex-wrap: wrap, items flow from top to bottom within a column, then wrap to the next column when they reach the container's fixed height. This creates a column-first fill order, which is the essence of masonry layout.

Key Requirements

  1. Fixed container height: The container must have a defined height for wrapping to occur. Without it, items would form a single infinitely tall column.
  2. Fixed item width: Items need a defined width since the column direction means flex-basis controls height, not width.
  3. Variable item heights: Each item should have natural or varied heights to create the masonry effect.

Limitations

This approach has significant limitations compared to true masonry:

Feature Flexbox Column True Masonry
Fill order Column-first (top to bottom) Row-first (left to right)
Container height Must be fixed Dynamic
Item order May not be intuitive Maintains reading order
Dynamic content Requires height recalculation Handles automatically

Making It Dynamic

To avoid a fixed container height, calculate it with CSS custom properties:

.masonry {
  --columns: 3;
  --total-height: 800px;
  height: var(--total-height);
}

Update --total-height via JavaScript or media queries for different content amounts.

Better Alternatives

For production masonry layouts, consider:

  • CSS Grid masonry (experimental, with grid-template-rows: masonry)
  • JavaScript libraries like Masonry.js or Isotope
  • CSS columns (simpler but less flexible)

Use Case

Use this technique for image galleries, portfolio showcases, or content feeds where items have varying heights and you want a dense, Pinterest-style column layout. Consider JavaScript-based solutions for dynamic content.

Try It — Flexbox Playground

Open full tool