0

I have content that I want to display over three columns. Each content is nested inside a box (div). Each box, has its own dynamic height (based on the content). My first approach was:

#boxes {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}

.box {
  background-color: #000;
}
<div id="boxes">
  <div class="box" style="height: 900px"></div>
  <div class="box" style="height: 200px"></div>
  <div class="box" style="height: 500px"></div>
  <div class="box" style="height: 400px"></div>
  <div class="box" style="height: 900px"></div>
  <div class="box" style="height: 100px"></div>
  <div class="box" style="height: 500px"></div>
  <div class="box" style="height: 200px"></div>
  <div class="box" style="height: 700px"></div>
  <div class="box" style="height: 300px"></div>
</div>

As you can see, it did split them into three columns, but there are lots of dead spaces between them. I'm trying to build a dynamic layout that will shrink between the boxes. Something like this:

enter image description here

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116
  • This [LINK](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout) can help you? – Simone Rossaini May 11 '20 at 12:48
  • in the question you can read the following *there is a trivial solution to this that works in modern browsers, the column-count property.* so column is considered as option there even if there is no explicit answer using it. – Temani Afif May 11 '20 at 12:53
  • @TemaniAfif Thanks. I wasn't aware of the term Masonry, hence I couldn't find the question before posting my own. – Eliya Cohen May 11 '20 at 12:55

1 Answers1

1

I got it working using column-count. I won't accept this answer because I'm interested to know if there's a better way of doing so.

#boxes {
  --gap: 16px;
  column-count: 3;
  column-gap: var(--gap);
}

.box {
  break-inside: avoid-column;
  margin-bottom: var(--gap);
  background-color: #000;
}
<div id="boxes">
  <div class="box" style="height: 900px"></div>
  <div class="box" style="height: 200px"></div>
  <div class="box" style="height: 500px"></div>
  <div class="box" style="height: 400px"></div>
  <div class="box" style="height: 900px"></div>
  <div class="box" style="height: 100px"></div>
  <div class="box" style="height: 500px"></div>
  <div class="box" style="height: 200px"></div>
  <div class="box" style="height: 700px"></div>
  <div class="box" style="height: 300px"></div>
</div>
Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116