如何中心javascript css弹出div,无论什么屏幕分辨率? [英] how do I center javascript css popup div, no matter what the screen resolution?
问题描述
我有下面的代码,打开一个新的弹出窗口,同时禁用背景,问题是,我必须将这个位置,使其从顶部(已经通过CSS #dialog)和中心的100px,也在中心
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?
<!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>
推荐答案
基于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 */
所以位置
应该指定。 top
和 left
应为 50%
。 margin-left
和 margin-top
应分别为框的宽度和高度的一半。
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.
请注意,如果您想让弹出式窗口显示在中心位置,即使页面滚动,您必须使用 position:fixed
而不是回退,它不工作在IE6。
Notice that if you want your popup to appear on center even when page is scrolled you will have to use position:fixed
instead with the draw back that it doesn't work in IE6.
这篇关于如何中心javascript css弹出div,无论什么屏幕分辨率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!