html - 嵌套的 flex 容器改变周围元素的对齐方式

标签 html css flexbox

我正在摆弄 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/

相关文章:

java - 在 HTML 标签之间提取数据

html - 希望内容以父为中心但 flex 包裹

html - 哪些工具可以自动内联CSS样式来创建电子邮件HTML代码?

html - FontAwesome悬停效果不起作用

jquery - 透明的 css 边框作为占位符

html - 如何扩展一个 div 以匹配 100% 的 CSS 父容器?

html - 使用 flexbox 将一个元素居中对齐,同时将其唯一的兄弟元素右对齐

javascript - Flexbox、 Canvas 和动态调整大小

html - Flexbox - 如果宽度改变,不要移动居中的列

javascript - 只显示一个类的第一次出现