将Flex项目垂直居中可在Chrome中运行但不适用于Firefox

时间:2016-12-07 00:12:21

标签: html css css3 firefox flexbox

我已经编写了这个简单的代码来集中我的内部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不居中。

火狐:

enter image description here

铬:

enter image description here

我需要内部div保持绝对定位。

2 个答案:

答案 0 :(得分:3)

重要的是要注意绝对定位的flex项参与flex布局。

来自规范:

  

4.1. Absolutely-Positioned Flex Children

     

因为它是一个流动的,一个绝对定位的flex的孩子   容器不参与flex布局。

换句话说,Flex容器(如代码中的align-items: center)之类的flex属性不受流出的flex项目的尊重。

您的商品在Chrome中居中显示只是因为Chrome定位了具有默认偏移值的绝对定位元素(即topbottomleft和{{ 1}}都设置为right。)Firefox将其置于其他位置。

要在所有浏览器中垂直居中您使用偏移属性:

&#13;
&#13;
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;
&#13;
&#13;

jsFiddle

有关使用CSS定位属性居中的更多详细信息,请参阅以下文章:

答案 1 :(得分:1)

对于您的给定HTML和CSS,内部<div>元素设置为position: absolute,您试图垂直居中从文档流中取出的div。

您可以选择一些解决方案。

选项1。

您可以将内部<div>设置为position: relative,并允许其父<div>align-items: center的行为正确应用于内部<div> {1}}(因为默认flex-directionrow)。然后,如果需要,您可以绝对在内部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,那么您可以在父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>