我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
这对我有用:
<div class="container><p>My text</p></div>
.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
其他回答
如果元素具有宽度和高度,则此解决方案有效
.包装器{宽度:300px;高度:200px;背景色:番茄;位置:相对;}.内容{宽度:100px;高度:100px;背景色:深蓝色;位置:绝对;顶部:0;右:0;底部:0;左:0;边距:自动;}<div class=“wrapper”><div class=“content”></div></div>
这适用于您希望在容器元素中心具有的绝对定位元素的任意未知宽度:
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;
}
HTML
<div id='parent'>
<div id='centered-child'></div>
</div>
CSS
#parent {
position: relative;
}
#centered-child {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto auto;
}
http://jsfiddle.net/f51rptfy/
我使用了类似的解决方案:
#styleName {
position: absolute;
margin-left: -"X"px;
}
其中“X”是要显示的div宽度的一半。它适用于所有浏览器。
这对我有用:
<div class="container><p>My text</p></div>
.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}