将模态对话框水平和垂直居中

Joh*_*acl 4 html css jquery modal-dialog

如何在页面中垂直和水平居中显示模态对话框?

ent*_*ull 10

一个jQuery解决方案,考虑模态对话框是绝对/相对/固定的位置:

var windowHeight = $(window).height();
var windowWidth = $(window).width();
var boxHeight = $('.modal-dialog').height();
var boxWidth = $('.modal-dialog').width();
$('.modal-dialog').css({'left' : ((windowWidth - boxWidth)/2), 'top' : ((windowHeight - boxHeight)/2)});
Run Code Online (Sandbox Code Playgroud)

一个jQuery解决方案,考虑到模态对话框,它不是绝对/相对/固定的位置:

CSS:

margin-left: auto;
margin-right: auto;
Run Code Online (Sandbox Code Playgroud)

jQuery的:

var windowHeight = $(window).height();
var boxHeight = $('.modal-dialog').height();
$('.modal-dialog').css({'margin-top' : ((windowHeight - boxHeight )/2)});
Run Code Online (Sandbox Code Playgroud)


小智 5

.modal-dialog {
    position: absolute;
    left: 50%;
    top: 50%;
    -moz-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

/* for IE 8 */
.modal-dialog.ie8 {
    /* you need to specify width and height */
    width: 500px; 
    height: 300px;
    margin-left: -150px; /* 300/2=150 */
    margin-top: -250px; /* 500/2=250 */
}
Run Code Online (Sandbox Code Playgroud)