Overlay window that appears in the center of the screen

I have JS code that fades the background to dark and opens a white modal window, for example:

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 that the screen does not display a dead point. I want the modal window to be dead center both vertically and horizontally, but I don’t know what width / height of the content inside the modal window will be, so I can’t set fixed values.

Any help is appreciated.

+5
source share
3 answers

You need to use these styles so that your white overlay displays a 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';

position. top left 50%. margin-left margin-top .

+17

, , , , .

Sarfraz, . ( ), :

    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

.

+4

( jquery - width(), height())

, , . , , .

You can also use a plugin like fancybox , which makes such things very simple.

+2
source

All Articles