I’m trying to create a responsive grid layout for images with variable number of elements, all in their original resolution, all centered in their cell. The largest image must be the reference, its cell must exactly fit it, and the grid has to be responsive to the space available (ie create rows only if necessary).
So far so good, the grid I ok for me, but with my approach, we must know the exact size of the largest square image if we want it to be the reference (with no space around).
Maybe it’s not possible to achieve this with pure CSS. I’m not able to, I hope you can give me some tips.
.gallery {
display: grid;
grid-gap: 1rem;
grid-template-columns: repeat(auto-fill, minmax(auto, 100px));
justify-items: center;
align-items: center;
}
.gallery img {
width: auto;
height: auto;
object-fit: scale-down;
object-position: center center;
}
<div class="gallery">
<img src="https://picsum.photos/25">
<img src="https://picsum.photos/50">
<img src="https://picsum.photos/75">
<img src="https://picsum.photos/100">
<img src="https://picsum.photos/25">
<img src="https://picsum.photos/50">
<img src="https://picsum.photos/75">
<img src="https://picsum.photos/100">
<img src="https://picsum.photos/25">
<img src="https://picsum.photos/50">
<img src="https://picsum.photos/75">
<img src="https://picsum.photos/100">
<img src="https://picsum.photos/25">
<img src="https://picsum.photos/50">
<img src="https://picsum.photos/75">
<img src="https://picsum.photos/100">
</div>
It should be great if I was not dependent of a hard-coded value (100px). Maybe we must compute it with a script, in very last solution.
2
Answers
snippet little better only but still 100px
Masonry layout still not implemented in grid, it’s coming but not yet.
After you could use masonry plug-in, check here:
https://masonry.desandro.com/
Or with javascript, getboudingclient rect you check all img size
Assuming you want to keep all the images same size as grid.