我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。

我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。

.center {
  left: 50%;
  bottom: 5px;
}

我怎样才能做到这一点?


当前回答

这是我想出的一个技巧,让DIV精确地浮在页面的中心。当然,它确实很难看,但它适用于所有浏览器。

点和虚线

<div style="border: 5 dashed red;position:fixed;top:0;bottom:0;left:0;right:0;padding:5">
    <table style="position:fixed;" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="width:200;border: 5 dashed green;padding:10">
                    Perfectly Centered Content
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

清洁工

哇,那五年刚刚过去,不是吗?

<div style="position:fixed;top:0px;bottom:0px;left:0px;right:0px;padding:5px">
    <table style="position:fixed" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="padding:10px">
                    <img src="Happy.PM.png">
                    <h2>Stays in the Middle</h2>
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

其他回答

.center {
  position: absolute
  left: 50%;
  bottom: 5px;
}

.center:before {
    content: '';
    display: inline-block;
    margin-left: -50%;
}

我使用了类似的解决方案:

#styleName {
    position: absolute;
    margin-left: -"X"px;
}

其中“X”是要显示的div宽度的一半。它适用于所有浏览器。

我只是想补充一句,如果有人想用一个div标记来完成,那么这里是解决方法:

宽度为900px。

#styleName {
    position: absolute;
    left: 50%;
    width: 900px;
    margin-left: -450px;
}

在这种情况下,应该事先知道宽度。

Flexbox可用于对绝对定位的div。

display: flex;
align-items: center;
justify-content: center;

.相对{宽度:275px;高度:200px;背景:皇家蓝;颜色:白色;边距:自动;位置:相对;}.绝对块{位置:绝对;高度:36px;背景:橙色;填充:0px 10px;底部:-5%;边框:1px实心黑色;}.居中文本{显示:柔性;对齐内容:中心;对齐项目:居中;盒子阴影:1px 2px 10px 2px rgba(0、0、0和0.3);}<div class=“relative center text”>相对块(Relative Block)绝对块</div></div>

响应式解决方案

假设div中的元素是另一个div。。。

此解决方案运行良好:

<div class="container">
  <div class="center"></div>
</div>

容器可以是任何大小(必须是相对位置):

.container {
    position: relative; /* Important */
    width: 200px; /* Any width */
    height: 200px; /* Any height */
    background: red;
}

元素(div)也可以是任何大小(必须小于容器):

.center {
    position: absolute; /* Important */
    top: 50%; /* Position Y halfway in */
    left: 50%; /* Position X halfway in */
    transform: translate(-50%,-50%); /* Move it halfway back(x,y) */
    width: 100px; /* Any width */
    height: 100px; /* Any height */
    background: blue;
}

结果将是这样的。运行代码段:

.容器{位置:相对;宽度:200px;高度:200px;背景:红色;}.中心{位置:绝对;顶部:50%;左:50%;转换:转换(-50%,-50%);宽度:100px;高度:100px;背景:蓝色;}<div class=“container”><div class=“center”></div></div>

我觉得这很有帮助。