JSFiddle - React, Tailwind, and code Playground
by Hastig Z
HTML
<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 class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
CSS
html, body {
margin: 0;
}
.container {
display: flex;
flex-wrap: wrap;
padding: 2px;
box-sizing: border-box;
}
.item {
display: flex;
width: calc(25% - 4px);
margin: 2px;
}
.item:nth-child(1) { height: 220px; background-color: blue; }
.item:nth-child(2) { height: 200px; background-color: green; }
.item:nth-child(3) { height: 180px; background-color: orange; }
.item:nth-child(4) { height: 240px; background-color: red; }
.item:nth-child(5) { height: 140px; background-color: pink; }
.item:nth-child(6) { height: 260px; background-color: yellow; }
.item:nth-child(7) { height: 210px; background-color: black; }
.item:nth-child(8) { height: 190px; background-color: purple; }
.item:nth-child(9) { height: 170px; background-color: grey; }
.item:nth-child(10) { height: 230px; background-color: violet; }
.item:nth-child(11) { height: 250px; background-color: silver; }
.item:nth-child(12) { height: 120px; background-color: gold; }
JavaScript
$(function() {
$('.item').each(function(index) {
if (index > 3) { // skip first 4
var itemAboveIndex = index - 4;
var itemAboveDistanceToTop = $('.item:eq('+itemAboveIndex+')').offset().top;
var itemAboveHeight = $('.item:eq('+itemAboveIndex+')').height();
var itemAboveBottomToTop = itemAboveDistanceToTop + itemAboveHeight;
var thisItemsTopDistanceFromTop = $(this).offset().top;
var distanceToAboveItem = thisItemsTopDistanceFromTop - itemAboveBottomToTop;
var marginOffset = parseInt(('-' + (distanceToAboveItem - 6) + 'px'), 10);
$(this).css('marginTop', marginOffset);
}
})
});