我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。
我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。
.center {
left: 50%;
bottom: 5px;
}
我怎样才能做到这一点?
当前回答
#container
{
position: relative;
width: 100%;
float: left
}
#container .item
{
width: 50%;
position: absolute;
margin: auto;
left: 0;
right: 0;
}
其他回答
绝对中心
HTML格式:
<div class="parent">
<div class="child">
<!-- content -->
</div>
</div>
CSS:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
演示:http://jsbin.com/rexuk/2/
它在Google Chrome、Firefox和Internet Explorer 8中进行了测试。
可以使用calc()将纵横比为1的元素与位置绝对值居中
在下面的示例中,我使用了一个圆,因为它更容易解释和理解,但相同的概念可以应用于任何具有纵横比的形状:1表示宽度和高度相等。(关于纵横比)
:根目录{--直径:80px;}第二部分{位置:绝对;顶部:计算(50%-var(--直径)/2);右:计算(50%-var(--直径)/2);纵横比:1;width:var(--直径);边界半径:100%;背景:蓝色;}<div/>
解释
这个问题的公认解决方案不适用于我的情况。。。
我正在为一些图片做字幕,我用这个解决了这个问题:
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>
我想补充一下bobince的回答:
<body>
<div style="position: absolute; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</body>
改进:///这使得水平滚动条不会在居中的div中出现大元素。
<body>
<div style="width:100%; position: absolute; overflow:hidden;">
<div style="position:fixed; left: 50%;">
<div style="position: relative; left: -50%; border: dotted red 1px;">
I am some centered shrink-to-fit content! <br />
tum te tum
</div>
</div>
</div>
</body>
我只是想补充一句,如果有人想用一个div标记来完成,那么这里是解决方法:
宽度为900px。
#styleName {
position: absolute;
left: 50%;
width: 900px;
margin-left: -450px;
}
在这种情况下,应该事先知道宽度。