Displaying photos that fill the grid - regardless of aspect ratio
18:20 10 Apr 2023

I am trying to create a photo gallery as a home learning project in react. I am able to display the photos in a grid:

enter image description here

Using this code:

const Container = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-gap: 10px;
justify-items: center;
align-items: center;
margin: 0;
padding: 0;
`

const PhotoWrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
height: 200px; /* set a fixed height for each grid item */
`

const Photo = styled.img`
max-width: 100%;
max-height: 100%;
object-fit: contain;
height: 100%; /* make the image fill the height of the grid item */
`

const Home = () => {

       return (
        
            
                {imagesData.map((image) =>  )}
            
           
    )
}

export default Home

That's NEARLY how I want it, but... I want it to be more like Flickr. Who do an AMAZING job at filling the grid without stretching photos (That I can tell).

Example: https://www.flickr.com/prints/discover

enter image description here

How do they manage to keep the rows the same length, and height? Is there some awesome CSS trick? Or is there maybe a load of backend work to calculate sizes and see what fits? How can I display my grid like that?

Edit: The solution accepted is amazing for what I need. Here's what it looks like for me now:

enter image description here

The only issue is when a small number of photos go onto the last row. The get cropped a lot, ad hard to see what they are. Is there a :last type class that could help this?

enter image description here

html css