Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay box appearing in the center of the screen

I have some JS code that fades the background to a dark colour and opens a white modal window, like so:

function open_litebox(link) {
    var overlay_black = 'position:absolute;top:0%;left:0%;width:100%;height:100%;background:black;z-index:1001;opacity:0.5;';
    $('body').append('<div style="' + overlay_black + '"></div>');
    var overlay_white = 'position:absolute;top:25%;left:25%;padding:5px;background-color:white;z-index:1002;overflow:auto;';
    $('body').append('<div style="' + overlay_white + '"><p>heeeyyy</p></div>');
}

But the problem is, it doesn't appear dead center in the screen. I want the modal window to be positioned in the dead center both vertically and horizontally, but I don't know what the width/height of the content inside the modal window is going to be so I can't set fixed values.

Any help is appreciated, cheers.

like image 717
Wen Avatar asked Nov 22 '10 20:11

Wen


1 Answers

You need to use these styles to make your white overlay appear dead-center:

var overlay_white = 'position:absolute;
                     top:50%;
                     left:50%;
                     background-color:white;
                     z-index:1002;
                     overflow:auto;
                     width:400px;
                     height:400px;
                     margin-left:-200px;
                     margin-top:-200px';

So position should be specified. The top and left should be 50%. The margin-left and margin-top should be negative one half of the width and height of the box respectively.

like image 72
Sarfraz Avatar answered Oct 20 '22 22:10

Sarfraz