我已经编写了这个简单的代码来集中我的内部div
:
<div style="display: flex;align-items: center;width: 100%;height: 600px;background-color: gray;">
<div style="background-color: white;width: 100px;height: 300px;position: absolute;"></div>
</div>
它在Chromium中运行良好。但不是在Firefox中。
在Firefox中,内部div不居中。
火狐:
铬:
我需要内部div保持绝对定位。
答案 0 :(得分:3)
重要的是要注意绝对定位的flex项不参与flex布局。
来自规范:
4.1. Absolutely-Positioned Flex Children
因为它是一个流动的,一个绝对定位的flex的孩子 容器不参与flex布局。
换句话说,Flex容器(如代码中的align-items: center
)之类的flex属性不受流出的flex项目的尊重。
您的商品在Chrome中居中显示只是因为Chrome定位了具有默认偏移值的绝对定位元素(即top
,bottom
,left
和{{ 1}}都设置为right
。)Firefox将其置于其他位置。
要在所有浏览器中垂直居中您使用偏移属性:
auto
&#13;
flex-container {
display: flex;
/* align-items: center; */
width: 100%;
height: 600px;
background-color: gray;
position: relative;
}
flex-item {
background-color: white;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
&#13;
有关使用CSS定位属性居中的更多详细信息,请参阅以下文章:
答案 1 :(得分:1)
对于您的给定HTML和CSS,内部<div>
元素设置为position: absolute
,您试图垂直居中从文档流中取出的div。
您可以选择一些解决方案。
您可以将内部<div>
设置为position: relative
,并允许其父<div>
将align-items: center
的行为正确应用于内部<div>
{1}}(因为默认flex-direction
是row
)。然后,如果需要,您可以绝对在内部div中定位内容。 codepen.io flex example
<强> CSS 强>
.container {
align-items: center;
background-color: #888;
display: flex;
height: 100vh;
width: 100%;
}
.inner {
background-color: #fff;
height: 100px;
position: relative;
width: 100px;
}
<强> HTML 强>
<div class="container">
<div class="inner"></div>
</div>
如果您确实需要内部<div>
为position: absolute
,那么您可以在父position: relative
元素上设置<div>
,然后设置top
和内部transform: translateY()
上的<div>
。 codepen.io position:absolute example
<强> CSS 强>
// display: flex and align-items: center
// are not needed to vertically align
// an element that is absolutely
// positioned
.container {
// align-items: center;
background-color: #888;
// display: flex;
height: 100vh;
position: relative;
width: 100%;
}
.inner {
background-color: #fff;
left: 0;
height: 100px;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100px;
}
<强> HTML 强>
<div class="container">
<div class="inner"></div>
</div>