我正在摆弄 flexbox,我注意到了一些奇怪的事情。
即使 CHILD 1 不在 flexbox 中,整个 .child
元素的位置也会发生变化,因为 .centervert
有一个垂直的 flexbox:
#cont {
background: blue;
}
.centervert {
display: flex;
flex-direction: column;
justify-content: center;
background: gray;
height: 100%;
}
.child {
display: inline-block;
width: 100px;
height: 100px;
background: green;
}
<div id="cont">
<div class="child">
CHILD 1
</div>
<div class="child ">
<div class="centervert">
CHILD 2
</div>
</div>
</div>
https://jsfiddle.net/d3ymxhe8/2/ :
如果您注释掉 display: flex
,CHILD 元素会按预期并排显示。但是对于 flex 显示,CHILD1 向下移动,以与 .centervert 的内容对齐。
什么给了?
最佳答案
当您将 child 2 的显示设置为 flex 并将文本垂直居中时,您导致 child 1 根据其默认的 vertical-align 属性自行调整,这对于内联元素是基线。您可以将 child1(以及 child2)的垂直对齐属性设置为类似 top 或 middle 的值,这将消除间隙。
#cont {
background: blue;
}
.centervert {
display: flex;
flex-direction: column;
justify-content: center;
background: gray;
height: 100%;
}
.child {
display: inline-block;
width: 100px;
height: 100px;
background: green;
vertical-align:middle;
}
<div id="cont">
<div class="child">
CHILD 1
</div>
<div class="child ">
<div class="centervert">
CHILD 2
</div>
</div>
</div>
关于html - 嵌套的 flex 容器改变周围元素的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44032126/