Masonry photo grid
in pure CSS

29th February 2020

This short article aims to show how it is possible to display a masonry photo grid only in HTML and CSS, without the help of Javascript, which remains elegantly aligned without being a too repetitive grid :

To realize this example, here is the HTML :

<div class="gallery">
<div><img src="2018.jpg" alt="2018" /></div>
<div><img src="2017.jpg" alt="2017" /></div>
<div><img src="2016.jpg" alt="2016" /></div>
<div class="narrow"><img src="2015.jpg" alt="2015" /></div>
<div><img src="2014.jpg" alt="2014" /></div>
<div class="narrow"><img src="2013.jpg" alt="2013" /></div>
<div><img src="2012.jpg" alt="2012" /></div>
<div><img src="2011.jpg" alt="2011" /></div>
<div class="narrow"><img src="2010.jpg" alt="2010" /></div>
<div><img src="2009.jpg" alt="2009" /></div>
<div><img src="2008.jpg" alt="2008" /></div>
<div><img src="2007.jpg" alt="2007" /></div>
<div><img src="2006.jpg" alt="2006" /></div>
</div>

And the CSS code:


@media only screen and (min-width: 550px) {
    .gallery {
        display: flex;
        width: 100%;
        flex-flow: row wrap;
        margin-left: -4px;
    }

    .gallery div {
        overflow: hidden;
        margin: 0 0 8px 8px;
        flex: auto;
        height: 250px;
        min-width: 150px;
    }

    .gallery div:nth-child(8n+1) {
        width: 310px;
    }

    .gallery div:nth-child(8n+2) {
        width: 270px;
    }

    .gallery div:nth-child(8n+3) {
        width: 260px;
    }

    .gallery div:nth-child(8n+4) {
        width: 310px;
    }

    .gallery div:nth-child(8n+5) {
        width: 240px;
    }

    .gallery div:nth-child(8n+6) {
        width: 190px;
    }

    .gallery div:nth-child(8n+7) {
        width: 210px;
    }

    .gallery div:nth-child(8n+8) {
        width: 170px;
    }

    .gallery div.wide {
        width: 650px;
    }

    .gallery div.tall {
        width: 650px;
        height: 450px;
    }

    .gallery div.narrow {
        width: 120px;
    }

    .gallery img {
        object-fit: cover;
        width: 100%;
        height: 100%;
    }
}

To have the images displayed in full screen at the click, you can consult the article Image overlay in pure CSS.

Photos credits: Wikimedia Pictures of the Year.