skip to Main Content

I want to create a responsive image gallery using flexbox where each row has images scaled to equal height while preserving aspect ratio and not cropping.

To highlight what I mean here are some placeholder images of various dimensions and the styling I tried:

.art-container {
  display: flex;
  flex-wrap: wrap;
}

.art-item {
  border-color: red;
  border-style: solid;
}

.art-item>img{
  min-height: 100%;
  width: auto;
}
<div class="art-container">
  <div class="art-item"> <img src='https://dummyimage.com/300x450/000/fff'></img></div>
  <div class="art-item"> <img src='https://dummyimage.com/600x400/000/fff'></img></div>
  <div class="art-item"> <img src='https://dummyimage.com/600x300/000/fff'></img></div>
  <div class="art-item"> <img src='https://dummyimage.com/600x400/000/fff'></img></div>
  <div class="art-item"> <img src='https://dummyimage.com/100x200/000/fff'></img></div>
  <div class="art-item"> <img src='https://dummyimage.com/200x100/000/fff'></img></div>
  <div class="art-item"> <img src='https://dummyimage.com/600x400/000/fff'></img></div>
</div>

Codepen

I used min-height: 100% and width: auto to scale all the images to the height of their row while preserving aspect ratio but this results in the image overflowing past its art-item container so the image gets cropped.

2

Answers


  1. So what you need to do is define each image to take up the same height. You could give art-item for example a height of 20vw. And then tell your images to take up 100% height. And since you already have width at auto for your images. They will take up the width proportional to the new calculated height.

    Login or Signup to reply.
  2. I think you have to set an explicit height for your rows. If this height has to be dynamic you have to set it via javascript.

    .art-container {
      display: flex;
      flex-wrap: wrap;
    }
    
    .art-item {
      border-color: red;
      border-style: solid;
      height: 200px;
    }
    
    img{
     height: 100%;
      width: auto;
    }
    <div class="art-container">
      <div class="art-item"> <img src='https://dummyimage.com/300x450/000/fff'></img></div>
      <div class="art-item"> <img src='https://dummyimage.com/600x400/000/fff'></img></div>
      <div class="art-item"> <img src='https://dummyimage.com/600x300/000/fff'></img></div>
      <div class="art-item"> <img src='https://dummyimage.com/600x400/000/fff'></img></div>
      <div class="art-item"> <img src='https://dummyimage.com/100x200/000/fff'></img></div>
      <div class="art-item"> <img src='https://dummyimage.com/200x100/000/fff'></img></div>
      <div class="art-item"> <img src='https://dummyimage.com/600x400/000/fff'></img></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search