在屏幕中间居中的div – 即使页面向上/向下滚动

我在我的页面中有一个button,当点击时在屏幕中间显示一个div(popup式样式)。

我正在使用下面的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; } 

只要页面没有向下滚动,它就可以正常工作。

但是,如果我把button放在我的页面底部,点击它,div显示在顶部(用户必须向上滚动查看div的内容)。

我想知道如何在屏幕中间显示div,无论用户是否向上/向下滚动。

position属性更改为fixed而不是absolute

改变position:absolute; position:fixed;

Quote :我想知道如何在屏幕中间显示div,无论用户是否向上/向下滚动。

更改

 position: absolute; 

 position: fixed; 

W3C position: absolute规格position: absolute position: fixedposition: fixed

我刚刚发现了一个新的窍门,即使没有固定的尺寸,也可以在屏幕中间放置一个盒子。 假设你想要一个60%宽度/ 60%高度的盒子。 使其居中的方法是创build2个框:位于左侧的“容器”框: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> 

好极了!

正确的方法是

 .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; }