【问题标题】:Vertically centering a flex item works in Chrome but not Firefox垂直居中弹性项目在 Chrome 中有效,但在 Firefox 中无效
【发布时间】:2017-04-21 19:02:27
【问题描述】:
我编写了这个简单的代码来集中我的内心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 保持绝对定位。
【问题讨论】:
标签:
html
css
firefox
flexbox
【解决方案1】:
请务必注意,绝对定位的弹性项目不参与弹性布局。
来自规范:
4.1. Absolutely-Positioned Flex
Children
由于它是外流的,因此是 flex 的绝对定位子代
容器不参与弹性布局。
换句话说,弹性容器上的align-items: center 之类的弹性属性(就像在您的代码中一样)不受流外弹性项目的影响。
您的项目在 Chrome 中显示为居中只是因为这是 Chrome 使用默认偏移值定位绝对定位元素的位置(即,top、bottom、left 和 right 都设置为 auto。) Firefox 将其放置在其他位置。
要在所有浏览器中垂直居中您的项目,请使用偏移属性:
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%);
}
<flex-container>
<flex-item></flex-item>
</flex-container>
有关使用 CSS 定位属性居中的更多详细信息,请参阅这篇文章:
【解决方案2】:
对于给定的 HTML 和 CSS,将内部 <div> 元素设置为 position: absolute,您正试图将一个从文档流中取出的 div 垂直居中。
您有几种解决方案。
选项 1。
您可以将内部<div> 设置为position: relative,这将允许其父<div> 正确地将align-items: center 的行为应用于内部<div>(因为默认flex-direction 是@987654331 @)。然后,如果需要,您可以绝对将内容定位在内部 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>
选项 2。
如果您确实需要内部<div> 为position: absolute,则可以在父<div> 元素上设置position: relative,然后在内部<div> 上设置top 和transform: translateY()。 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>