Grizzy: How to create a Grid Gallery using modern CSS

on in Blog
Last modified on

In this article, we are going to create a grid gallery using CSS only, more precisely Flexbox CSS.

In the past, I used a light, responsive JavaScript library called Gridzy. I still use it on some websites. This time, though, we’ll eliminate JavaScript and use CSS only.

Grizzy Grid Gallery CSS

Let’s see why this technique is preferred over a JavaScript alternative:

  • It’s light and fast
  • It’s mobile responsive
  • It’s SEO-optimized out of the box
  • It doesn’t use media queries
  • It needs 21 lines of functional CSS

Let’s get to it.

Let’s build the image container, which is a simple, semantic unordered list. This technique works for 10+ images, especially if you have a large screen resolution or us the full width of your website for the image container.

<ul class="grizzy--grid">
    <li><img src="#" alt=""></li>
    <li><img src="#" alt=""></li>
    <li><img src="#" alt=""></li>
</ul>

Let’s style the <li> elements and the images inside:

.grizzy--grid {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -8px -8px 0;
    padding: 0;
}
.grizzy--grid li {
    height: 200px;
    flex-grow: 1;
    margin: 0 8px 8px 0;
    list-style: none;
    padding: 0;
}
.grizzy--grid li:last-child {
    flex-grow: 10;
}
.grizzy--grid img {
    max-height: 100%;
    min-width: 100%;
    object-fit: cover;
}

Note how we style the <li> elements as Flex elements, and then place the images inside using the object-fit: cover property to fill the entire cell.

That’s all! Isn’t it amazing?

Let’s micro-optimize it a bit:

  • If the gallery is below the fold, lazy load your images
  • If you want to optimize your images for Google (or Bing), add a title attribute
  • Optimize your images (we prefer TinyJPG and TinyPNG)
  • Minify your CSS for 267 bytes
<ul class="grizzy--grid">
    <li><img src="#" alt="" title="" loading="lazy"></li>
    <li><img src="#" alt="" title="" loading="lazy"></li>
    <li><img src="#" alt="" title="" loading="lazy"></li>
</ul>
.grizzy--grid{display:flex;flex-wrap:wrap;margin:0 -8px -8px 0;padding:0}.grizzy--grid li{height:200px;flex-grow:1;margin:0 8px 8px 0;list-style:none;padding:0}.grizzy--grid li:last-child{flex-grow:10}.grizzy--grid img{max-height:100%;min-width:100%;object-fit:cover}

Resize the browser window to see how the images resize and stack.

  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery
  • Grizzy Grid Gallery

Or checkout the CodePen demo:

See the Pen Flex Grid by Ciprian (@ciprian) on CodePen.

Related posts