无论屏幕分辨率如何,我如何将 javascript css 弹出 div 居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11021766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:03:46  来源:igfitidea点击:

how do I center javascript css popup div, no matter what the screen resolution?

javascriptcsspopup

提问by user1227914

I have the following code that opens a new popup window while disabling the background, the problem is that I have to position this so that it's 100px from the top (already got that through the CSS #dialog) and also in the center of the screen, no matter what the user's resolution is?

我有以下代码可以在禁用背景的同时打开一个新的弹出窗口,问题是我必须将其定位为距顶部 100 像素(已经通过 CSS #dialog 获得)并且位于屏幕中央,不管用户的分辨率是多少?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <script type="text/javascript">
        function showPopUp(el) {
            var cvr = document.getElementById("cover")
            var dlg = document.getElementById(el)
            cvr.style.display = "block"
            dlg.style.display = "block"
            if (document.body.style.overflow = "hidden") {
                cvr.style.width = "1024"
                cvr.style.height = "100%"
            }
        }
        function closePopUp(el) {
            var cvr = document.getElementById("cover")
            var dlg = document.getElementById(el)
            cvr.style.display = "none"
            dlg.style.display = "none"
            document.body.style.overflowY = "scroll"
        }
    </script>
    <style type="text/css">
        #cover {
            display:        none;
            position:       absolute;
            left:           0px;
            top:            0px;
            width:          100%;
            height:         100%;
            background:     gray;
            filter:         alpha(Opacity = 50);
            opacity:        0.5;
            -moz-opacity:   0.5;
            -khtml-opacity: 0.5
        }

        #dialog {
            display:    none;
            left:       100px;
            top:        100px;
            width:      300px;
            height:     300px;
            position:   absolute;
            z-index:    100;
            background: white;
            padding:    2px;
            font:       10pt tahoma;
            border:     1px solid gray
        }
    </style>
</head>
<body>
<div id="cover"></div>
<div id="dialog">
    My Dialog Content
    <br><input type="text">
    <br><input type="button" value="Submit">
    <br><a href="#" onclick="closePopUp('dialog');">[Close]</a>
</div>
<a href="#" onclick="showPopUp('dialog');">Show</a>

</body>
</html>

回答by Sarfraz

CSS basedsolution to center:

基于 CSS 的居中解决方案:

You need to use these styles to make it appear dead-center:

您需要使用这些样式使其看起来死心:

position:absolute;
top:50%;
left:50%;
width:400px;  /* adjust as per your needs */
height:400px;   /* adjust as per your needs */
margin-left:-200px;   /* negative half of width above */
margin-top:-200px;   /* negative half of height above */

So positionshould be specified. The topand leftshould be 50%. The margin-leftand margin-topshould be negative one half of the width and height of the box respectively.

所以position应该指定。该topleft50%。的margin-leftmargin-top应该是负一盒子的宽度和高度分别一半。

Notice that if you want your popup to appear on center even when page is scrolled you will have to use position:fixedinstead with the draw back that it doesn't work in IE6.

请注意,如果您希望弹出窗口即使在页面滚动时也显示在中心,您将不得不使用position:fixed它在 IE6 中不起作用的缺点。

回答by tsikov

What you need is called a light-box.

你需要的是一个灯箱

To create it you should modify HTML,CSS and JS code.

要创建它,您应该修改 HTML、CSS 和 JS 代码。

Let's say your lightbox consist only of the string "login form". (You can put everything you want there) The HTML code should look like this:

假设您的灯箱仅包含字符串“登录表单”。(你可以把你想要的一切放在那里)HTML 代码应该是这样的:

<div id = "loginBox">login form</div>

Now, we need to hide it with CSS:

现在,我们需要用 CSS 隐藏它:

div#loginBox {
    display: none;
}

Now our box is not visible. Lets modify our box as you want it to be 100px from the top:

现在我们的盒子是不可见的。让我们修改我们的框,因为你希望它离顶部 100 像素:

div#loginBox {
    display: none;
    top: 100px;
}

We will worry about disabling the background later.

我们稍后会担心禁用后台。

Our next job is to make a button that will display the box when we need it. Easy-peasy:

我们的下一个工作是制作一个按钮,当我们需要它时会显示这个框。十分简单:

<div id = "loginBox" >login form</div>
<a id = "displayButton">login</a>

Note that we don't need the "href" attribute, because that will move the screen on clicking and other unwanted behavior.

请注意,我们不需要“href”属性,因为它会在点击和其他不需要的行为时移动屏幕。

Let's attach event handler on the button via JS:

让我们通过 JS 在按钮上附加事件处理程序:

var IE = document.all ? true : false; // obligatory "browser sniffing"

function display_box() {
    document.getElementsById("loginBox").style.display = "inline-block"; // or "inline" 
}

window.onload = function() {
    var login_box = document.getElementsById("loginBox");
    if (!IE) {
        login_box.addEventListener( "click", display_box , false );
    }
    else {
        login_box.attachEvent( "onclick", display_box );
    }
}

But you want it to be in the center of the screen? Then the function goes like this:

但是您希望它位于屏幕中央?然后函数是这样的:

function display_box() {
    var theBox = document.getElementsById("loginBox").style,
        left = document.width / 2 - 50;   // 150 because it is 300 / 2

    theBox.display = "inline-block";
    theBox.left = left.toString() + "px";
}

I would guess that you will want to close the window at some point and make the "disabled background" effect. To do so you can create a div class that extends on the whole screen, attach a "display" event on it, put some z-index in the css to be sure the loginBox is over the "disabled background", and attach a "close the loginBox" event on the "background" div. And now the final code looks like this:

我猜你会想在某个时候关闭窗口并制作“禁用背景”效果。为此,您可以创建一个在整个屏幕上扩展的 div 类,在其上附加一个“显示”事件,在 css 中放置一些 z-index 以确保 loginBox 位于“已禁用的背景”之上,并附加一个“关闭“背景”div 上的 loginBox”事件。现在最终的代码如下所示:

Note that we care only about the placement of the login-button, because the other are hidden from view, and then modified by JS:

注意我们只关心 login-button 的位置,因为其他的都是隐藏的,然后被 JS 修改:

HTML:

HTML:

<div id = "loginBox" >login</div>
<a id = "displayButton">login</a>
<div id = "backgroundDarkener"> </div>

CSS:

CSS:

div#loginBox {
    display: none;
    top: 100px;
    width: 300px; #it is important to know the width of the box, to center it correctly
    z-index: 2;
}
div#backgroundDarkener {
    background: #000;
    display: none;
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    z-index: 1;
    opacity: 0.8; 
    # needless to say, you should play with opacity or if you want your
    # css to validate - background image (because I suspect it won't 
    # validate for old versions of IE, Safari, etc.) This is just a suggestion
}

JS:

JS:

var IE = document.all ? true : false; // obligatory "browser sniffing"

function display_box() {
    var theBox = document.getElementsById("loginBox").style,
        background = document.getElementsById("loginBox").style,
        left = document.width / 2 - 150;   // 150 is 300 / 2

    theBox.display = "inline-block";
    theBox.left = left.toString() + "px";
    background.display = "inline-block";
}
function hide_box() {
    document.getElementsById("loginBox").style.display = "none";
    document.getElementsById("backgroundDarkener").style.display = "none"; 
}

window.onload = function() {
    var login_box = document.getElementsById("loginBox"),
        background = document.getElementsById("backgroundDarkener");

    if (!IE) {
        login_box.addEventListener( "click", display_box , false );
        background.addEventListener( "click", hide_box , false );
    }
    else {
        login_box.attachEvent( "onclick", display_box );
        background.attachEvent( "onclick", hide_box );
    }
}

回答by Celso Soares

Just do this:

只需这样做:

.body {
    position: relative;
}
.popup {
    position: absolute;
    max-width: 800px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

no matters the screen or popup size. This will center the <div class="popup"></div>.

无论屏幕或弹出窗口大小。这将使<div class="popup"></div>.

回答by Ankur Tiwari

This is where flexbox comes rescue now!

这就是 flexbox 现在来拯救的地方!

.parent {
  display: flex;
  height: 300px; /* Or whatever */
}

.child {
  width: 100px;  /* Or whatever */
  height: 100px; /* Or whatever */
  margin: auto;  /* Magic! */
}

回答by John Conde

A quick Google search found this;

一个快速的谷歌搜索找到了这个

function PopupCenter(pageURL, title,w,h) {
  var left = (screen.width/2)-(w/2);
  var top = (screen.height/2)-(h/2);
  var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);

} 

回答by lnegi

You need to use these styles to make div center:

您需要使用这些样式来使 div 居中:

width:500px; 
left:0;
right:0;
margin:0 auto;

回答by Madara's Ghost

Simple, margin: 100px auto;. There's no need to do calculations in JavaScript.

简单,margin: 100px auto;。无需在 JavaScript 中进行计算。

Live Example

现场示例