Monday, November 30, 2015

Pop a Message Box in the Center with Transparent Background Curtain using Fixed DIV and CSS


This is a very popular method to pop up a small window at the center of a page to ask for user's registration or something that requires visitors' special attention. The following codes will not freeze the scroll bars or any movement on the page:

<!DOCTYPE HTML>
<html>

<style type="text/css">

#curtain {
left:0px;
top:0px;
filter:alpha(opacity=70);
-moz-opacity:0.7;
opacity:0.7;
width: 100%;
height: 100%;

}

#message_box {
left:50%;
top:50%;
width: 200px;
height: 70px;
z-index: 1;
margin-top: -35px; /* 70/2 * -1 */
margin-left: -100px; /* 200/2 * -1 */
}

div > div#curtain { position: fixed; }
div > div#message_box { position: fixed; }

</style>

<script>

function close() {
document.getElementById('curtain').style.visibility = "hidden";
document.getElementById('message_box').style.visibility = "hidden";
}


</script>


<body bgcolor="#aabbcc">


<div style="width:100%;height:100%;">

<div id="message_box" style="border:1px solid #333; background-color:#ddd; text-align:center; padding:10px; ">
<p>Message Here<br><a href="javascript:close()">Close</a></p>
</div>

<div id="curtain" style="background-color:#ddd;"> </div>

</div>



<table width="95%" align=center><tr><td>
<br>line 1<br>line 2<br>line 3<br>line 4<br>line 5<br>line 6<br>line 7<br>line 8<br>line 9<br>line 10
<br>line 11<br>line 12<br>line 13<br>line 14<br>line 15<br>line 16<br>line 17<br>line 18<br>line 19<br>line 20
<br>line 21<br>line 22<br>line 23<br>line 24<br>line 25<br>line 26<br>line 27<br>line 28<br>line 29<br>line 30
<br>line 31<br>line 32<br>line 33<br>line 34<br>line 35<br>line 36<br>line 37<br>line 38<br>line 39<br>line 40
<br>line 41<br>line 42<br>line 43<br>line 44<br>line 45<br>line 46<br>line 47<br>line 48<br>line 49<br>line 50
<br>line 51<br>line 52<br>line 53<br>line 54<br>line 55<br>line 56<br>line 57<br>line 58<br>line 59<br>line 60
<br>line 61<br>line 62<br>line 63<br>line 64<br>line 65<br>line 66<br>line 67<br>line 68<br>line 69<br>line 70
</td></tr></table>


</body>

</html>


Here is a screenshot of the HTML ran on a Google Chrome browser:



As for the scroll bars freezing or movement stalling versions, they will be presented in the coming posts. This post is all about the transparent engulfing DIV and the pop-up window at the center of it.

Please note that in order to fix the message box to the center of the page, the margin-top and margin-left CSS properties are used. If these margins are not implemented, the upper left corner of the message box will be at the center of the page. The margin is the negative value of the half of the height or width of the box.

Javascript is also used to hide the message box when the "close" link is clicked. At the same time, the curtain is also removed when the message box is hidden.

No comments:

Post a Comment