search

Home  >  Q&A  >  body text

CSS: Rendering 4 items in 2 columns using Columns: 3

I want to create a 3 column masonry layout to render items with the same width but different heights, but when I try the code below, I see that the third column is empty, which looks a little weird. Can I fix it somehow?

I tried this code, I want to have two items in the first column and one item in the second and third columns. Please note that 4 items of the same height is just a specific case, ultimately I don't know how many items there will be and the height of each item.

.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>

P粉300541798P粉300541798447 days ago513

reply all(1)I'll reply

  • P粉281089485

    P粉2810894852023-09-09 12:16:59

    For this case, you can combine display: flex with flex-wrap: wrap and justify-content: space- Between using containers

    .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>

    reply
    0
  • Cancelreply