JSFiddle - React, Tailwind, and code Playground
HTML
Example wont work:
<div id="wrapper">
<div class="d_1">1</div>
<div class="d_2">2</div>
<div class="d_3">3</div>
<div class="d_4">4</div>
<div class="d_5">5</div>
<div class="d_6">6</div>
<div class="d_7">7</div>
<div class="d_8">8</div>
<div class="d_9">9</div>
</div>
CSS
#wrapper{
width:200px;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-column-gap: 10px;
grid-row-gap: 5px;
}
#wrapper div{
background-color:lightgray;
width:50px;
}
.d_1{
height:60px;
}
.d_2{
height:30px;
}
.d_3{
height:33px;
}
.d_4{
height:70px;
}
.d_5{
height:60px;
}
.d_6{
height:40px;
}
.d_7{
height:20px;
}
.d_8{
height:20px;
}
.d_9{
height:90px;
}
JavaScript
function compute_gaps(a){
let max = a.max();
return a.map(function(el){return el-max;});
}
function compose_gaps(a, b) {
return b.map(function(el,i){return a[i]+el;});
}
var counter = 0;
var columns = 3;
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
var gaps = [];
var heights = [];
for (let el of document.querySelectorAll("#wrapper > div")) {
let colIdx = counter % columns;
if (counter % columns == 0){
//compute gaps
counter != 0 && gaps.push(compute_gaps(heights));
if (gaps.length>1) {
gaps[gaps.length-1]=compose_gaps(gaps[gaps.length-1], gaps[gaps.length-2]);
}
heights = [];
}
if (gaps.length){
el.style.marginTop = gaps[Math.floor(counter / columns - 1)][colIdx];
}
heights.push(el.offsetHeight);
counter++
}