JSFiddle - React, Tailwind, and code Playground
by izno
HTML
<div class="box">1</div>
<div class="box" style="margin-left: 30px">2</div>
<div class="box" style="margin-left: 90px">3</div>
<div class="box" style="margin-left: 120px">4</div>
<div class="box" style="margin-left: 140px">5</div>
<div class="box" style="margin-left: 100px">6</div>
<div class="box" style="margin-left: 20px">7</div>
<div class="box" style="margin-left: 150px">8</div>
<div class="box" style="margin-left: 130px">9</div>
CSS
.box {
height: 50px;
width: 50px;
border: 1px solid black;
text-align: center;
margin-bottom: 5px;
/**/
position: absolute;
/*/
display: inline-block;
/**/
}
JavaScript
var top = 5; // top value for next row
var margin = 5; // space between rows
var rows = []; // list of rows
function float_top() {
for (var c = 0; c < document.body.children.length; c++) {
var ok = false;
var child = document.body.children[c];
var cr = child.getBoundingClientRect();
for (var i = 0; i < rows.length; i++) {
if (cr.left > rows[i].right) {
rows[i].right = cr.right;
child.style.top = rows[i].top + "px";
ok = true;
break;
}
if (cr.right < rows[i].left) {
rows[i].left = cr.left;
child.style.top = rows[i].top + "px";
ok = true;
break;
}
}
if (!ok) {
// add new row
rows.push({
top: top,
right: cr.right,
left: cr.left
});
child.style.top = top + "px";
top = child.getBoundingClientRect().bottom + margin;
}
}
}
float_top();