Search code examples
htmlcssgrid-layout

How to make a responsive image grid which changes image size depending on the amount of images?


I'm trying to make a responsive grid of images which makes the images smaller when there are multiple next to each other and larger when there is, for instance, only one image.

(For better understanding here below are some photos of expected results)

Photo 1:

enter image description here

Photo 2:

enter image description here

I've tried playing with the max-width and min-width and using various display modes but no luck. Furthermore, I've tried looking on the internet but no luck there too.

.photos .content {
  width: 70%;
  min-height: 100%;
  margin-left: 15%;
  background-color: #F5F5F5;
}

.photos .content .grid {
  display: overflow: none;
}

.photos img {
  max-width: 30%;
  min-width: 25%;
  height: 30%;
}
<div class="panel photos">
  <div class="content" id="photos">
    <div class="grid">
      <img src="img/sample-images/sample1.jpg">
      <img src="img/sample-images/sample2.jpg">
      <img src="img/sample-images/sample3.jpg">
    </div>
  </div>
</div>


Solution

  • I am assuming that there are 3 images on first row and 3 in second row.

    Don't give width of the image as 30%, instead give it 100%

    So that it will reduce the size as per the viewport

    .grid {
      display: grid;
      grid-template-columns : repeat(3,1fr);
      grid-template-rows: repeat(2, 20vw);
      grid-gap: 10px;
    }
    
    .grid_image {
      width:100%;
      height:100%;
      object-fit:cover;
    }
    

    CodePen link