JSFiddle - React, Tailwind, and code Playground
HTML
<div id='main'></div>
CSS
#main {
position:relative;
width:300px;
height:300px;
}
div:not(#main){
background-color:black;
width:100px;
height:100px;
}
JavaScript
var
div={},
number=10,
size=100,
m = ele('main');
mw= parseFloat(getComputedStyle(m).getPropertyValue("width"))-size,
mh= parseFloat(getComputedStyle(m).getPropertyValue("height"))-size,
f=true;
var newX,nn, newY;
var i
for (i = 0; i < number; i++) {
div[i] = {};
var t = true;
if (i!=0){
while (t) {
newX = rand(mw);
newY = rand(mh);
for (nn = 0; nn < i; nn++) {
if (!(((newX > div[nn].x + size) || (newY > div[nn].y + size)) ||
((newX + size < div[nn].x) || (newY + size < div[nn].y)))) {
break;
}
if (nn == i-1) t = false;
}}} else {
newX = rand(mw);
newY = rand(mh);
}
console.log(newX);
div[i].x = newX;
div[i].y = newY;
}
for (i = 0; i < number; i++) {
render(div[i]);
}
console.log(div);
function render(x){
var d=document.createElement('div');
d.style.position='absolute';
d.style.left=(x.x+'px');
d.style.top=(x.y+'px');
m.appendChild(d);
}
function rand(x) { return Math.random()*x;}
function ele(x){return document.getElementById(x);}