我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
这适用于您希望在容器元素中心具有的绝对定位元素的任意未知宽度:
Demo
<div class="container">
<div class="box">
<img src="https://picsum.photos/200/300/?random" alt="">
</div>
</div>
.container {
position: relative;
width: 100%;
}
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
}
其他回答
这个问题的公认解决方案不适用于我的情况。。。
我正在为一些图片做字幕,我用这个解决了这个问题:
top: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
display: flex;
align-items: center;
数字{位置:相对;宽度:325px;显示:块}图标题{位置:绝对;背景:#FFF;宽度:120px;填充:20px;-webkit框阴影:0 0 30px灰色;方框阴影:0 0 30px灰色;边界半径:3px;显示:块;顶部:0;左:0;右:0;左边距:自动;右边距:自动;显示:柔性;对齐项目:居中;}<图><img src=“https://picsum.photos/325/600"><figcaption>但也一样</figcaption></figure>
.center {
position: absolute
left: 50%;
bottom: 5px;
}
.center:before {
content: '';
display: inline-block;
margin-left: -50%;
}
这是我想出的一个技巧,让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>
一个简单的方法,对我来说,可以将一个未知宽度的块水平居中:
<div id="wrapper">
<div id="block"></div>
</div>
#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
#block {
display: inline-block;
}
文本对齐属性可以添加到#block规则集,以独立于块的对齐方式对齐其内容。
这在Firefox、Chrome、Internet Explorer、Edge和Safari的最新版本上有效。
我只是想补充一句,如果有人想用一个div标记来完成,那么这里是解决方法:
宽度为900px。
#styleName {
position: absolute;
left: 50%;
width: 900px;
margin-left: -450px;
}
在这种情况下,应该事先知道宽度。