0

I have a flex container that contains dynamically generated items. These items can be of different heights every time the page is regenerated and - as a result - the spacing between the items is always different.

While each item's distance to its siblings should be a constant 20px (on all sides), if one of its siblings is larger or smaller, the gap between them increases.

Without targeting every single element and manually adjusting their position, is there a way I can ensure that each item has exactly 20px between it and its siblings? Like this.

/* Important CSS */
.container{
    display: flex;
    flex-grow: 1;
    flex-basis: 0;
    flex-wrap: wrap;
    align-items: flex-start;
    row-gap: 20px;
    column-gap: 20px;
}

.item{
    flex-basis: 30%;
    flex-grow: 1;
    height: 50px;
    background: red;
}

/* Dont worry about this bit */
.container{
    width: 600px;
}
/* To emulate dynamically generated content */
.item:nth-child(2),
.item:nth-child(6){
    height: 60px;
}
<div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>
GROVER.
  • 4,071
  • 2
  • 19
  • 66

1 Answers1

0

Seems to be a work for grid's masonry layout. But it's not supported on all browsers (It only works on Mozilla Firefox currently). But a workaround you could use is by using the column-count property. See the snippet below:

/* Important CSS */

.container {
  column-count: 3;
  column-gap: 20px;
}

.item {
  margin: 0;
  display: grid;
  grid-template-rows: 1fr auto;
  margin-bottom: 20px;
  break-inside: avoid;
  height: 50px;
  background: red;
}


/* Dont worry about this bit */

.container {
  width: 600px;
}


/* To emulate dynamically generated content */

.item:nth-child(2),
.item:nth-child(6) {
  height: 80px;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

More on it on this website.

Yong
  • 1,622
  • 1
  • 4
  • 29