'Make a flexbox container with wrapped items scrollable

I have a grid of images that are spaced into columns dynamically using flex-wrap: wrap. However there is one problem, I don't know how to make the container scrollable because it has a dynamic height. I have searched for solutions to this problem but I don't really know how to adapt them for my use case.

This is my code:

.imagegrid {
    display: flex;
    width: 100%;
    height: 100%;
    background-color: var(--background);
}

.image-container {
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
    flex-wrap: wrap;
    justify-content: space-between;
    padding-left: 30px;
    padding-right: 30px;
}

.image {
    width: auto;
    max-height: 270px;
    margin-bottom: 10px;
    cursor: pointer;
}

I want to make either the image-container or imagegrid scrollable on the y-axis.

This is the HTML, if needed:

<div class="imagegrid">
  <div class="image-container">
    <img class="image" src="image"/>
    <img class="image" src="image2"/>
    (multiple images)
  </div>
</div>

The images are added dynamically from a database. I do not know what the height of the container will be.


Solution 1:[1]

In order for elements to scroll vertically you must do 2 things

  • Give them an explicit height that makes them have to scroll
  • Give them an overflow setting of auto or scroll

I've added a working example with both applied:

.imagegrid {
  display: flex;
  width: 100%;
  height: 200px;
  overflow: auto;
  background-color: var(--background);
}

.image-container {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  flex-wrap: wrap;
  justify-content: space-between;
  padding-left: 30px;
  padding-right: 30px;
}

.image {
  width: auto;
  max-height: 270px;
  margin-bottom: 10px;
  cursor: pointer;
}
<div class="imagegrid">
  <div class="image-container">
    <img class="image" src="https://source.unsplash.com/random/200x200" />
    <img class="image" src="https://source.unsplash.com/random/250x250" /> (multiple images)
  </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zach Jensz