垂直居中Flex项目在Chrome中,但不是Firefox [英] Vertically centering a flex item works in Chrome but not Firefox

查看:208
本文介绍了垂直居中Flex项目在Chrome中,但不是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布局

从规范:


4.1。绝对定位的Flex
儿童


由于流水不足,一个绝对定位的flex
容器不参与flex布局。

换句话说,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



<




I've written this simple code for centering my inner 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>

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 align-items: center on the flex container (like in your code) are not respected by out-of-flow flex items.

Your item appears centered in Chrome simply because that's where Chrome positions an absolutely positioned element with default offset values (i.e., top, bottom, left and right are all set to auto.) Firefox positions it somewhere else.

To vertically center your item in all browsers use the offset properties:

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

For more details about centering with CSS positioning properties see this post:

这篇关于垂直居中Flex项目在Chrome中,但不是Firefox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆