Search code examples
cssimagegrid

Css grid image gallery - vertical images take up too much space


I have a responsive css grid gallery, and the veritical images mess up my layout, they appear at full size. I want them to stay square, as the other ones. How do i do that? Thank you!

Here is the code:

  <div id="gallery">
    <a   href="001.jpg"><img class="image" src="001.jpg"  ></a>
  <a   href="002.jpg"><img class="image" src="002.jpg"  ></a>
  <a   href="003.jpg"><img class="image" src="003.jpg"  ></a>
 <a   href="004.jpg"><img class="image" src="004.jpg"  ></a>


#gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(50rem, 1fr));
  column-gap: 10px;
  row-gap: 10px;
  margin: 0px 30px;
  top: 0px;
  height: 100%;
  align-items: stretch;
}
.image {
  display: block;
  width: 100%;
  margin: 0px;
 
  
}

I want them to stay square, as the other ones. How do i do that? Thank you!


Solution

  • If your goal is to have all images in the grid appear square regardless of their original dimensions, you could use aspect-ratio and object-fit on your .image class.

    .image {
        display: block;
        width: 100%;
        margin: 0px; 
        /* Add these */   
        aspect-ratio: 1;
        object-fit:cover;
    }