首页 文章

中心div位于屏幕中间 - 即使页面向上/向下滚动

提问于
浏览
110

我的页面中有一个按钮,单击该按钮会在屏幕中间显示一个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;
}

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

但是,如果我将按钮放在页面底部并单击它,则div显示在顶部(用户必须向上滚动才能查看div的内容) .

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

5 回答

  • 3

    position 属性更改为 fixed 而不是 absolute .

  • 30

    position:absolute; 更改为 position:fixed;

  • 5

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

    更改

    position: absolute;
    

    position: fixed;
    

    W3C specifications for position: absolute and for position: fixed.

  • 16

    即使你没有固定的尺寸,我也发现了一个新的技巧,可以将一个盒子放在屏幕中间 . 假设你想要一个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>
    

    好极了!

  • 166

    正确的方法是

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

相关问题