I know the different approaches to a masonry layout. Here, I’m working with images which dimensions are known. For quite long I’ve used a layout based on absolute positions, with success. But I’d like to gain some flexibility. I’m currently exploring an alternate way based on CSS grid layout.
So I’m using CSS Grid to layout images of different heights in two columns. Images positions in the grid are explicit. Images are set to span one or more rows depending on there height compared to other images. I’d like my columns not to have any empty space in them. But in the resulting layout, some of the rows heights are bigger than necessary to account for the content.
I’ve built an example using aspect-ratio
to mimic images intrinsic ratio and a reduce set of items:
<style>
ul {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 2px;
margin: 10px;
padding: 0;
}
li {
align-items: center;
background: lightgrey;
border: 2px solid red;
display: flex;
flex-flow: column;
font-size: 24px;
justify-content: center;
}
li:nth-child(1) {
grid-area: 1/1/2/2;
}
li:nth-child(2) {
grid-area: 1/2/3/3;
}
li:nth-child(3) {
grid-area: 2/1/4/2;
}
li:nth-child(4) {
grid-area: 3/2/5/3;
}
li:nth-child(5) {
grid-area: 4/1/6/2;
}
</style>
<ul>
<li style="aspect-ratio:0.87086092715232">1</li>
<li style="aspect-ratio:0.63680387409201">2</li>
<li style="aspect-ratio:1.5748502994012">3</li>
<li style="aspect-ratio:0.7874251497006">4</li>
<li style="aspect-ratio:0.63680387409201">5</li>
</ul>
Here is what I get:
What I want and expected was a solid layout :
I can’t understand why, except for the two first rows, the next rows are taller than strictly required to fit the content. My understanding of grid layout is not yet good. I’ve fumbled around fit-content
and min-content
in the list’s grid-template-rows
and item’s height
properties without any success.
My issue is really similar to that one, but it is old and does not give a solution to collapse theses gaps. So is there a way to obtain a solid grid layout with auto row heights?
I’m interested in grid layout solutions only.