How to create an image gallery with Grid and only two CSS classes

For my latest article I wanted to create a matrix of photos and the grid layout option of CSS came into the rescue. With only two CSS classes, one for the grid itself and one for the grid cells you can create a beautiful image gallery for your website.

We are also going to see how to apply the grid on Markdown code and how to change the way the grid is presented on mobile devices.

First we want to define the CSS code. Read further for explanation of what each property does.

  .image-container {
    display: grid;
    grid-gap: 1em;
  }

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

  .grid-2-1 {
    grid-template-columns: repeat(2, 1fr);
	  grid-template-rows: repeat(1, 1fr);
  }

  .grid-2-2 {
	  grid-template-columns: repeat(2, 1fr);
	  grid-template-rows: repeat(2, 1fr);
  }

We now integrate the CSS class in our Markdown code by using this syntax: {: .image-container.grid-2-1 }. We defined that our grid will have two columns and one row.

Finally we want all the images to be presented vertically when we view the website from our mobile device. For that we are going to use some more CSS and define a @media screen property. We are going to override the value for the number of columns and set it to 1.

  @media screen and (max-width: 767px) {
    .grid-2-1, .grid-2-2 {
      grid-template-columns: repeat(1, 1fr);
      grid-template-rows: repeat(1, 1fr);
    }
  }

To vertically position the images inside a grid cell we can also use the align-items: self-end property which would put the grid items on the bottom of each cell.

comments powered by Disqus