我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
一个简单的方法,对我来说,可以将一个未知宽度的块水平居中:
<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的最新版本上有效。
其他回答
HTML格式:
<div class="wrapper">
<div class="inner">
content
</div>
</div>
CSS:
.wrapper {
position: relative;
width: 200px;
height: 200px;
background: #ddd;
}
.inner {
position: absolute;
top: 0; bottom: 0;
left: 0; right: 0;
margin: auto;
width: 100px;
height: 100px;
background: #ccc;
}
这里还有更多的例子。
只需使用一个新的div包装您的内容并使用display flex,然后使用align-items:center;并调整内容:中心;看看。。。
<div class="firstPageContainer">
<div class="firstPageContainer__center"></div>
</div>
.firstPageContainer{
display: flex;
width: 1000px;
height: 1000px;
justify-content: center;
align-items: center;
background-color: #FF8527;
}
.firstPageContainer__center{
position:absolute;
width: 50px;
height: 50px;
background-color: #3A4147;
}
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>
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/
这适用于您希望在容器元素中心具有的绝对定位元素的任意未知宽度:
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;
}