To create the most common masonry layout, your columns will be the grid axis and the rows the masonry axis, defined with grid-template-columns
and grid-template-rows
. The child elements of this container will now lay out item by item along the rows, as they would with regular grid layout automatic placement.
As the items move onto new rows, they will display according to the masonry algorithm. Items will load into the column with the most room, causing a tightly packed layout without strict row tracks.
.grid {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
grid-template-rows: masonry;
}
<div class="grid">
<div class="item" style="block-size: 2em;"></div>
<div class="item" style="block-size: 3em;"></div>
<div class="item" style="block-size: 1.6em;"></div>
<div class="item" style="block-size: 4em;"></div>
<div class="item" style="block-size: 2.2em;"></div>
<div class="item" style="block-size: 3em;"></div>
<div class="item" style="block-size: 4.5em;"></div>
<div class="item" style="block-size: 1em;"></div>
<div class="item" style="block-size: 3.5em;"></div>
<div class="item" style="block-size: 2.8em;"></div>
</div>
It is also possible to create a masonry layout with items loading into rows.
.grid {
display: grid;
gap: 10px;
grid-template-columns: masonry;
grid-template-rows: repeat(3, 100px);
}