CSS Grid & Flexbox
Hey everyone, I'm struggling to achieve a masonry-style layout where grid items can rise up and fill in the gaps left by varying item heights. See added screenshots. Here's the breakdown:
Problem: I've been trying to create a responsive layout where the grid items move up to fill in the empty spaces above them, much like a masonry layout. However, neither Flexbox with flex-wrap nor CSS Grid with grid-auto-flow: dense are working as expected.
Cause: The issue seems to be with the way Flexbox and Grid are handling the vertically staggered items. Flexbox doesn't seem to support this feature at all (since its 1-dimensional and all), and while CSS Grid has a dense keyword, it's not producing the desired masonry effect.
Attempts:
I've used display: flex; with flex-wrap: wrap; and justify-content: space-between; in Flexbox.
I've tried using CSS Grid with grid-auto-flow: row dense;.
I've also experimented with different grid-template-columns and grid-auto-rows settings.
Code:
css
/* Flexbox attempt /
.grid {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1rem;
}
.grid-item {
flex-grow: 1;
margin-bottom: 1rem;
float: left;
word-break: break-all;
}
/ CSS Grid attempt */
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
grid-auto-rows: auto;
grid-auto-flow: row dense;
gap: 1rem;
}
.grid-item {
margin-bottom: 1rem;
}
Any advice or insight would be greatly appreciated!
I’m guessing this needs some JS-solution however.