I’m trying to create masonry layout using css grid layout. All items in grid have variable heights. The items in the next row should stack to available space of the items in the previous row. i tried using flex-flow: row wrap
but it doesn’t work. Below is what i’m trying to achive.
Html Markup:
<div class="container">
<div class="g grid-33">Item 1</div>
<div class="g grid-66">Item 2</div>
<div class="g grid-33">Item 3</div>
<div class="g grid-33">Item 4</div>
<div class="g grid-33">Item 5</div>
<div class="g grid-66">Item 6</div>
<div class="g grid-33">Item 7</div>
</div>
CSS
.container {
display: flex;
flex-wrap: wrap;
padding: 15px 15px 0 0;
background: #CDD6D0;
}
.g {
background: #E16036;
border: 4px solid #E3170A;
border-radius: 8px;
padding: 15px;
color: white;
font: 18px Arial;
margin: 0 0 15px 15px;
height: fit-content;
}
.grid-25 {
width: calc(25% - 15px);
}
.grid-33 {
width: calc(33.3333% - 15px);
}
.grid-50 {
width: calc(50% - 15px);
}
.grid-66 {
width: calc(66.6666% - 15px);
}
.grid-100 {
width: calc(100% - 15px);
}
.g:nth-child(2) {
height: 100px;
}
.g:nth-child(3) {
height: 90px;
}
.g:nth-child(6) {
height: 100px;
}
.g:nth-child(5) {
height: 90px;
}
2
Answers
I was able to create your image with the grid system with the code below using the grid system as was hinted by you with a grid 3fr wide and 8fr long.
widths
To create the width items with class grid-33 have span 1 fraction and items with class grid-66 span 2 fractions in width
heights
in your picture item 1, 4 and 7 are around 2 / 3ths of the the other items. Because of this there height is set to 2 fractions and the remaining are set to 3 fractions.
gaps
To keep the correct gaps I kept your margins as grid-gap didnt seem to work.
and to give the items the correct height I changed heigth to auto, so there are no empty spaces.
There is an upcoming specification that adds masonry layout to the grid module of CSS. Unfortunately it is not supported by any browser yet: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout/Masonry_layout
In my VueJS apps I’m using the following plugin for masonry layout: https://vue-masonry-wall.yeger.eu/ It works well enough.
Maybe you can dig into the code and figure out how it’s done in native JS/CSS.