【问题标题】:Does 'position: absolute' conflict with Flexbox?'position: absolute' 是否与 Flexbox 冲突?
【发布时间】:2017-04-23 07:52:37
【问题描述】:

我想在屏幕顶部制作一个div,而不影响其他元素,并且它的子元素在中心。

 .parent {
   display: flex;
   justify-content: center;
   position: absolute;
 }
<div class="parent">
  <div class="child">text</div>
</div>

当我添加position: absolute 行时,justify-content: center 变得无效。它们是否相互冲突,解决方案是什么?

编辑

谢谢大家,这是父宽度的问题。但是我在 React Native 中,所以无法设置 width: 100%。试过flex: 1align-self: stretch,都不起作用。我最终使用Dimensions 来获得窗口的整个宽度并且它起作用了。

编辑

对于较新版本的 React Native(我使用的是 0.49),它接受 width: 100%

【问题讨论】:

标签: css react-native flexbox


【解决方案1】:

在我的例子中,问题是我在 div 的中心有另一个元素的 z-index 冲突。

.wrapper {
  color: white;
  width: 320px;
  position: relative;
  border: 1px dashed gray;
  height: 40px
}

.parent {
  position: absolute;
  display: flex;
  justify-content: center;
  top: 20px;
  left: 0;
  right: 0;
  /* This z-index override is needed to display on top of the other
     div. Or, just swap the order of the HTML tags. */
  z-index: 1;
}

.child {
  background: green;
}

.conflicting {
  position: absolute;
  left: 120px;
  height: 40px;
  background: red;
  margin: 0 auto;
}
<div class="wrapper">
  <div class="parent">
    <div class="child">
       Centered
    </div>
  </div>
  <div class="conflicting">
    Conflicting
  </div>
</div>

【讨论】:

    【解决方案2】:

    不,绝对定位与弹性容器不冲突。让一个元素成为一个弹性容器只会影响它的内部布局模型,即它的内容的布局方式。定位会影响元素本身,并且可以改变其在流布局中的外部角色。

    也就是说

    • 如果使用display: inline-flex 为元素添加绝对定位,它将变为块级(如display: flex),但仍会生成弹性格式化上下文。

    • 如果您使用 display: flex 为元素添加绝对定位,则将使用收缩匹配算法(典型的内联级容器)而不是可用填充算法调整其大小。

    也就是说,absolutely positioning conflicts with flex children

    由于它是外流的,因此是 flex 的绝对定位子代 容器不参与弹性布局。

    【讨论】:

      【解决方案3】:

      你忘记了父母的宽度

      .parent {
         display: flex;
         justify-content: center;
         position: absolute;
         width:100%
       }
      <div class="parent">
        <div class="child">text</div>
      </div>

      【讨论】:

        【解决方案4】:

        您必须将 width:100% 给父 center 文本。

         .parent {
           display: flex;
           justify-content: center;
           position: absolute;
           width:100%
         }
        <div class="parent">
          <div class="child">text</div>
        </div>

        如果还需要垂直居中对齐,给height:100%align-itens: center

        .parent {
           display: flex;
           justify-content: center;
           align-items: center;
           position: absolute;
           width:100%;
           height: 100%;
         }
        

        【讨论】:

          猜你喜欢
          • 2018-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-18
          • 2013-01-23
          • 2021-07-26
          相关资源
          最近更新 更多