-1

I have a container, which contains blocks inside. The number of the blocks and their height can be different, but the width is 45% for all, so that two blocks can fit into one row. I currently use flexbox with flex-wrap: wrap, but there is an issue, which you can see on the screenshot below. The wanted result is the one on the right. How can that be achieved?

Example

HTML:

.container {
      display: flex;
      flex-wrap: wrap;
    }
    
    .block {
      width: 45%;
      border: 1px solid black;
      background-color: grey;
    }
 <div class="container">
      <div class="block" style="height: 500px;"></div>
      <div class="block" style="height: 200px;"></div>
      <div class="block" style="height: 100px;"></div>
      <div class="block" style="height: 300px;"></div>
      <div class="block" style="height: 500px;"></div>
    </div>


    
Sean
  • 936
  • 4
  • 15
Kromel
  • 89
  • 4
  • 1
    Not sure about for specific use case, maybe this [`dense` value](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow) might help – Loi Nguyen Huynh Apr 22 '21 at 03:49
  • 1
    As there are javascript libraries to achieve this [masonary effect](https://masonry.desandro.com/layout.html), I doubt it can currently be done with HTML and CSS alone. – Jon P Apr 22 '21 at 04:30

1 Answers1

0

What you want is quite tricky and might be close to impossible but there's a way to somehow do it. If your container's height is fixed at some point, you can just set the flex-direction of your container to column then set the max height for the container as a brake point to go to new column. See sample code below. You can run it.

.container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  max-height: 900px;
}

.block {
  width: 45%;
  border: 1px solid black;
  background-color: grey;
}
<div class="container">
  <div class="block" style="height: 500px;"></div>
  <div class="block" style="height: 200px;"></div>
  <div class="block" style="height: 100px;"></div>
  <div class="block" style="height: 300px;"></div>
  <div class="block" style="height: 500px;"></div>
</div>
JkAlombro
  • 1,696
  • 1
  • 16
  • 30