используйте относительное как Положение.
function on() {
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
.row {
position: relative;
}
#overlay {
position: absolute;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 2;
cursor: pointer;
}
<div class="row">
<div id="overlay" onclick="off()"></div>
<div style="padding:20px; border: 3px solid black;" id="my_main_div">
<h2>Overlay</h2>
<p>Add an overlay effect to the page content (100% width and height with a black background color with 50% opacity).</p>
<button onclick="on()">Turn on overlay effect</button>
</div>
</div>