使用CSS将弹出窗口居中

时间:2015-11-11 12:37:50

标签: html css

我正试图将这个弹出窗口集中在一起,但我似乎无法让它在像iphone这样的小屏幕上正常工作。它在桌面/笔记本电脑屏幕上看起来不错。任何人都可以建议任何想法如何使用媒体查询让弹出窗口正确居中,无论屏幕大小?感谢。

    <style type="text/css">
    #popup {
        display: none;
        background: #FFF;
        border: 5px solid #444;
        padding: 0 15px 15px 15px;
        position: fixed;
        top: 20%;
        left:35%;
        width: 25%;
        min-width: 210px;
        z-index: 100000;
        box-shadow: 0 0 10px #000;
        border-radius: 5px;
        text-align: center;
    }
    #popup-overlay {
        display: none;
        background: #000;
        opacity: 0.5;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 99999;
    }
</style>

5 个答案:

答案 0 :(得分:1)

最简单的方法是使用变换使元素居中。无论元素的宽度/高度

,这都可以

&#13;
&#13;
html, body {
    height: 100%;
    margin: 0;
}

#popup {
    /*display: none;*/
    background: #FFF;
    border: 5px solid #444;
    padding: 15px;
    position: fixed;
    width: 25%;
    min-width: 210px;
    z-index: 100000;
    box-shadow: 0 0 10px #000;
    border-radius: 5px;
    text-align: center;
    top: 50%;
    left:50%;
    transform: translate(-50%, -50%)
}
#popup-overlay {
    /*display: none;*/
    background: #000;
    opacity: 0.5;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 99999;
}
&#13;
<div id="popup-overlay"></div>
<div id="popup">Look at me!</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你能试试吗,

#popup {
    display: none;
    background: #FFF;
    border: 5px solid #444;
    padding: 0 15px 15px 15px;
    position: fixed;
    top: 20%;
    left: 50%;
    width: 25%;
    margin-left: -25%;
    min-width: 210px;
    z-index: 100000;
    box-shadow: 0 0 10px #000;
    border-radius: 5px;
    text-align: center;
    box-sizing: border-box;
}

注意: 最好添加一些像url这样的jsfiddle而不是提供易于理解和锻炼的部分细节。

答案 2 :(得分:0)

left:50%;
margin-left:-120px;

(210/2)+ 15 = 120

答案 3 :(得分:0)

我会将物体移动到中心,然后向右移动一半大小。

由于对象宽度未修复,请使用transform执行此操作:

#popup {
       ...
       left:50%;
       transform: translate(-50%);
       ...
       }

尽管IE8及以下版本中没有transform,但可能是一个很好的解决方案。

http://jsfiddle.net/fvLtd068/

答案 4 :(得分:0)

对于支持html5的浏览器,请使用:

&#13;
&#13;
#popup {
    background: #FFF;
    border: 5px solid #444;
    padding: 0 15px 15px 15px;
    position: fixed;
    /* top: 20%; */ //Remove
    /* left: 35%; */ //Remove
    /* width: 25%; */ //Remove
    left: 50%; // Insert
    top: 50%; // Insert
    transform: translate3d(-50%, -50%, 0); // Insert
    min-width: 210px;
    z-index: 100000;
    box-shadow: 0 0 10px #000;
    border-radius: 5px;
    text-align: center;
}
&#13;
&#13;
&#13;