tan*_*nya 119 html css scroll position centering
我的页面中有一个按钮,单击该按钮会div在屏幕中间显示(弹出式样式).
我使用以下CSS来居中div在屏幕中间:
.PopupPanel
{
border: solid 1px black;
position: absolute;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;
width: 600px;
margin-left: -300px;
}
Run Code Online (Sandbox Code Playgroud)
只要页面不向下滚动,此CSS就可以正常工作.
但是,如果我将按钮放在我的页面底部,当它被点击时,它div会显示在顶部,用户必须向上滚动才能查看该内容div.
我想知道如何div在屏幕中间显示,即使页面已滚动.
Spa*_*rky 16
Quote:我想知道如何在屏幕中间显示div,用户是否向上/向下滚动.
更改
position: absolute;
Run Code Online (Sandbox Code Playgroud)
至
position: fixed;
Run Code Online (Sandbox Code Playgroud)
W3C规范适用于position: absolute和position: fixed.
即使你没有固定的尺寸,我也发现了一个新的技巧,可以将一个盒子放在屏幕中间.假设你想要一个60%宽度/ 60%高度的盒子.使其居中的方法是创建2个框:一个位于左侧的"容器"框:50%顶部:50%,内部有一个"文本"框,左侧反向位置:-50%; 上:-50%;
它工作,它是跨浏览器兼容的.
看看下面的代码,你可能会得到更好的解释:
<div id="message">
<div class="container"><div class="text">
<h2>Warning</h2>
<p>The message</p>
<p class="close"><a href="#">Close Window</a></p>
</div></div>
<div class="bg"></div>
</div>
<style type="text/css">
html, body{ min-height: 100%; }
#message{ height: 100%; left: 0; position: fixed; top: 0; width: 100%; }
#message .container{ height: 60%; left: 50%; position: absolute; top: 50%; z-index: 10; width: 60%; }
#message .container .text{ background: #fff; height: 100%; left: -50%; position: absolute; top: -50%; width: 100%; }
#message .bg{ background: rgba(0,0,0,0.5); height: 100%; left: 0; position: absolute; top: 0; width: 100%; z-index: 9; }
</style>
<script type="text/javascript">
jQuery('.close a, .bg', '#message').on('click', function(){
jQuery('#message').fadeOut();
return false;
});
</script>Run Code Online (Sandbox Code Playgroud)
好极了!
正确的方法是
.PopupPanel
{
border: solid 1px black;
position: fixed;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;
height: 400px;
margin-top: -200px;
width: 600px;
margin-left: -300px;
}
Run Code Online (Sandbox Code Playgroud)