Creating a pure CSS masonry layout (without JavaScript) can be achieved using CSS Columns or CSS Grid. Below are two common methods:
If you need better support, CSS Columns can create a masonry effect.
.container {
column-count: 3; /* Adjust the number of columns based on your design */
column-gap: 1rem; /* Space between columns */
width: 100%; /* Full width of the container */
}
.item {
break-inside: avoid; /* Prevent items from splitting across columns */
padding: 1rem;
margin-bottom: 1rem; /* Space between items */
background-color: #f2f2f2; /* Example background color */
padding: 1rem; /* Padding inside items */
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
<div class="container">
<div class="item size-1">1</div>
<div class="item size-3">2</div>
<div class="item size-4">3</div>
<div class="item size-2">4</div>
<div class="item size-3">5</div>
<div class="item size-1">6</div>
</div>
Here is a live example:
✅ Pros: Simple, works in all major browsers.
❌ Cons: Items flow top to bottom (not row-wise), making ordering unpredictable.
CSS Grid now supports masonry layout natively in Firefox, but it’s not yet widely supported in all browsers. Here’s a fallback-friendly way:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-auto-rows: 10px; /* Controls vertical spacing */
gap: 10px;
}
.item {
background: lightblue;
border-radius: 8px;
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
}
/* Dynamic height for masonry effect */
.item:nth-child(1) { grid-row: span 10; }
.item:nth-child(2) { grid-row: span 15; }
.item:nth-child(3) { grid-row: span 12; }
.item:nth-child(4) { grid-row: span 18; }
.item:nth-child(5) { grid-row: span 8; }
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
Here is a live example:
✅ Pros: Works well with CSS Grid, responsive, minimal code.
❌ Cons: Requires manual row spans for height control.
Note that CSS Grid Layout Level 3 includes a masonry feature:
grid-template-rows: masonry;
Unfortunatly, this feature is not supported by browsers. See Browser compatibility for more information.