垂直居中Flex项目在Chrome中,但不是Firefox [英] Vertically centering a flex item works in Chrome but not Firefox
问题描述
我已经写了这个简单的代码来定位我的内部 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不居中。
$ b
Firefox:
Chromium:
我需要内部div保持绝对定位。
重要的是要注意绝对定位的flex项目不要 参与flex布局。 从规范: 由于流水不足,一个绝对定位的flex 换句话说,flex属性,比如 要在所有浏览器中垂直居中您的项目,请使用偏移属性: I've written this simple code for centering my inner
And it works fine in Chromium. but not in Firefox. In Firefox the inner div is not centered. Firefox: Chromium: I need the inner div to remain absolutely positioned. It's important to note that absolutely positioned flex items do not participate in flex layout. From the spec: 4.1. Absolutely-Positioned Flex
Children As it is out-of-flow, an absolutely-positioned child of a flex
container does not participate in flex layout. In other words, flex properties, such as Your item appears centered in Chrome simply because that's where Chrome positions an absolutely positioned element with default offset values (i.e., To vertically center your item in all browsers use the offset properties:
For more details about centering with CSS positioning properties see this post: 这篇关于垂直居中Flex项目在Chrome中,但不是Firefox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
容器不参与flex布局。
align您的物品(如您的代码中)上的物品:中心
不受流出弹性物品的限制。 出现在Chrome浏览器的中心,只是因为Chrome浏览器使用默认偏移值(即 top
, bottom
, left 和
right
都设置为 auto
。) Firefox将它定位在其他地方。
flex-container {display:flex; / * align-items:center; * /宽度:100%; height:600px;背景颜色:灰色; position:relative;} flex-item {background-color:white;宽度:100px; height:100px;位置:绝对;顶部:50%; transform:translateY(-50%);}
<柔性容器> < flex-item>< / flex-item>< / flex-container>
jsFiddle
<
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>
align-items: center
on the flex container (like in your code) are not respected by out-of-flow flex items.top
, bottom
, left
and right
are all set to auto
.) Firefox positions it somewhere else.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>
jsFiddle