CSS: 4 items rendered in 2 columns when using column-count: 3

177 Views Asked by At

I wanted to create a masonry layout of 3 columns to render items with same width but different height but then when I tried the code bellow I saw the third column is empty which seems a bit weird. can I fix it somehow?

I tried this code and I expect two items in first column, and one item in the second and third column. note that 4 items with same height is just a specific case, in the end I don’t how many items there will be and what height each item will have.

.container {
  column-count: 3;
  background-color: #f7f7f7;
  width: 588px
}

.item {
  width: 180px;
  height: 180px;
  break-inside: avoid;
  background-color: #e5e5e5;
  margin-bottom: 20px;
}
<div class="container">
  <div class="item">
    1
  </div>
  <div class="item">
    2
  </div>
  <div class="item">
    3
  </div>
  <div class="item">
    4
  </div>
</div>

1

There are 1 best solutions below

2
antonylgs On

For that case, you can use a display: flex with flex-wrap: wrap and justify-content: space-between on the container

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  background-color: #f7f7f7;
  width: 588px
}

.item {
  width: 180px;
  height: 180px;
  break-inside: avoid;
  background-color: #e5e5e5;
  margin-bottom: 20px;
}
<div class="container">
  <div class="item">
    1
  </div>
  <div class="item">
    2
  </div>
  <div class="item">
    3
  </div>
  <div class="item">
    4
  </div>
</div>