'position: absolute' 是否与 Flexbox 冲突? [英] Does 'position: absolute' conflict with Flexbox?

查看:58
本文介绍了'position: absolute' 是否与 Flexbox 冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 .parent {显示:弹性;对齐内容:居中;位置:绝对;}

<div class="child">text</div>

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

编辑

谢谢大家,这是父宽度的问题.但是我使用的是 React Native,所以我无法设置 width: 100%.尝试了 flex: 1align-self:stretch,都不起作用.我最终使用 Dimensions 来获取窗口的全宽和它工作.

编辑

从较新版本的 React Native(我是 0.49)开始,它接受 width: 100%.

解决方案

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

这意味着

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

  • 如果您使用 display: flex 向元素添加绝对定位,则将使用缩小以适应算法(典型的内联级容器)而不是填充来调整其大小- 可用一个.

也就是说,绝对定位与弹性子项冲突.

<块引用>

因为它是流外的,一个绝对定位的 flex 子节点容器不参与弹性布局.

I want to make a div stick on the top of the screen without any influence to other elements, and its child element in the center.

 .parent {
   display: flex;
   justify-content: center;
   position: absolute;
 }

<div class="parent">
  <div class="child">text</div>
</div>

When I add the position: absolute line, justify-content: center becomes invalid. Do they conflict with each other and, what's the solution?

EDIT

Thanks guys it's the problem of parent width. But I'm in React Native, so I can't set width: 100%. Tried flex: 1 and align-self: stretch, both not working. I ended up using Dimensions to get the full width of the window and it worked.

EDIT

As of newer version of React Native (I'm with 0.49), it accepts width: 100%.

解决方案

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

这篇关于'position: absolute' 是否与 Flexbox 冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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