Every time I refresh the page, the positioning of the child div
sometimes overflow
or position itself outside the parent div
. Any ideas of how to prevent this? I tried playing around with size of the child div
as well as its "top"
and "left"
values without any luck.
Here is the code:
#box {
width: 1000px;
height: 400px;
background-color: grey;
margin: 0;
padding: 0;
}
#shape {
display: none;
position: relative;
}
</style>
</head>
<body>
<div id="box">
<div id="shape"></div>
</div>
<script>
function makeShapeAppear() {
var top = Math.floor(Math.random() * 301);
var left = Math.floor(Math.random() * 901);
var size = Math.floor(Math.random() * 101) + 50;
document.getElementById("shape").style.display = "block"
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = size + "px";
document.getElementById("shape").style.height = size + "px";
document.getElementById("shape").style.backgroundColor = "red";}
</script>
</body>
Thank you in advance.
The reason this occurs is because you do not take into account the random size of the child.
var size = Math.floor(Math.random() * 101) + 50;
That line can produce a size up to 150.
var top = Math.floor(Math.random() * 301);
That line can set the top at a maximum of 300.
The parent div is only 400px tall, so if the size gets computed at 150 and the top at 300 the child will overflow the parent on the bottom by 50px. A similar situation occurs when setting left that will cause the child to overflow on the right of the parent. You need to constrain top and left. Example below.
function makeShapeAppear() {
var size = Math.floor(Math.random() * 101) + 50;
var top = Math.min(Math.floor(Math.random() * 101), 180 - size);
var left = Math.min(Math.floor(Math.random() * 301), 400 - size);
document.getElementById("shape").style.display = "block"
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = size + "px";
document.getElementById("shape").style.height = size + "px";
document.getElementById("shape").style.backgroundColor = "red";
setTimeout(function() { makeShapeAppear(); }, 1000);
}
makeShapeAppear();
#box {
width: 400px;
height: 180px;
background-color: grey;
margin: 0;
padding: 0;
}
#shape {
display: none;
position: relative;
}
<div id="box">
<div id="shape"></div>
</div>