
Here’s a simple truth about modal box: It is ridiculously easy to be made.
The Logic
Basically, modal box is a ‘flying’ box on top of another content. To achieve this kind of state, all you need is:
- Create a wrapper which is positioned on top of everything. Utilize the usage of
position:fixed, 100%width&height,top&leftandz-index(if it is needed) - Create the ‘box’ inside the wrapper. Place your content within it. Utilize the usage of
margin: autoto adjust its position - You want to show it only if user click particular link, right? great, now
display:noneit. - Using javascript (i’m using jQuery), show the wrapper if particular DOM is clicked.
- The modal box need to be hidden after its content is read. Using javascript, create a functionality which makes the wrapper hidden if particular DOM is clicked.
The HTML Markup

Place this code anywhere you want. I’d rather place it on the bottom of the page, though.
<div id="modal-background"> <div id="modal-box"> <h2>This is the modalbox</h2> <p>Paragraph Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <a href="#" id="close-modal">Close this modal box</a> </div> </div>
The CSS
The trick: style it on modal-box-is-shown state first. If the styling has been okay, display:none it.
#modal-background {position:fixed; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.8); display:none;}
#modal-box {display:block; background:#fff; width:400px; padding:20px; margin:100px auto; box-shadow:0 0 10px #efefef;}
#modal-box h2 {margin-top:0;}
The JavaScript, using jQuery
Use the beauty of jQuery’s fadeIn() and fadeOut() in setting display:block and display:none a DOM.
$(document).ready(function() {
$('#show-modal').click(function(){
$('#modal-background').fadeIn();
return false;
});
$('#close-modal').click(function(){
$('#modal-background').fadeOut();
return false;
});
});
The Demo
And that’s that. Here’s the demo:
Demo of Simple Do-It-Yourself Modal Box
As usual, please take a look at its page source code for further explanation. Hope it helps
Marcio
04 October 2011
very cool! tanks!
fikrirasyid
06 October 2011
The pleasure is mine
Yrvandi
14 November 2011
amazing
simple but powerfull