如何使用Javascript对齐pop up div [英] How to center align pop up div using Javascript
问题描述
如何使用javascript将弹出部门与显示器/屏幕中心对齐?
我尝试使用screen.width和screen.height获取中心。但是该部门垂直对齐滚动页面的中心
提前感谢任何帮助和建议
< div id =popupclass =popup> ;
这是一个垂直和水平居中的弹出窗口。
< / div>
< a onclick =showPopup('popup');> Show Popup< / a>
< style type =text / css>
.popup {
宽度:200px;
身高:100px;
仓位:绝对;
top:50%;剩余
:50%;
保证金:-50px 0 0 -100px; / * [ - (height / 2)px 0 0 - (width / 2)px] * /
display:none;
}
< / style>
< script type =text / javascript>
函数showPopup(id){
var popup = document.getElementById(id);
popup.style.display ='block';
}
< / script>
CSS解释:
div是200x100,你的位置它从顶部50%,从左边50%,但要完全居中,你需要从50%的值减去宽度和高度的一半,这样做的方法是使用负边距,因此边缘-top应该是height / 2的负值,margin-left应该是width / 2的负值。
How to align a pop up division to center of monitor/screen using javascript?
I tried using screen.width and screen.height to get center. But the division gets aligned to center of scrolling page vertically
Thanks in advance for any help and suggestions
Try this:
<div id="popup" class="popup">
This a vertically and horizontally centered popup.
</div>
<a onclick="showPopup('popup');">Show Popup</a>
<style type="text/css">
.popup {
width:200px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
display:none;
}
</style>
<script type="text/javascript">
function showPopup(id) {
var popup = document.getElementById(id);
popup.style.display = 'block';
}
</script>
CSS explained: The div is 200x100, you position it 50% from the top and 50% from the left, but to have it centered fully, you need to substract from that 50% values the half of the width and height, the way to do this is to use negative margins, hence margin-top should be the negative value of the height/2 and margin-left should be the negative value of the width/2.
这篇关于如何使用Javascript对齐pop up div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!