【问题标题】: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: 1 和align-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>
【解决方案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%;
}