html - 为什么 Flexbox 不垂直居中?

标签 html css flexbox

尝试让视频帧在浏览器中垂直和水平对齐。这是我所拥有的...

body {
  height:100%;
  width:100%;
}

#frame {
  display: flex;
  align-items: center;
  justify-content: center;
}

.video {
  width: 80%;
}
<div id="frame">
  <div class="video">
    <iframe  width="1200" height="675" src="https://www.youtube.com/embed/dQw4w9WgXcQ?ecver=1" frameborder="0"></iframe>
  </div>
</div>

视频水平居中,但不垂直居中。

最佳答案

元素#frame与内容(.video)具有相同的高度:

body {
  height:100%;
  width:100%;
}
#frame {
  border:1px dotted red;
  display:flex;
  align-items:center;
  justify-content:center;
}
.video {
  border:1px dotted blue;
  line-height:0;
  width:80%;
}
<div id="frame">
  <div class="video">
    <img src="https://placehold.it/100x75"/>
  </div>
</div>

因此 .video 垂直居中,但您看不到它!如果您为 #frame 添加的高度大于内容 (.video),您可以看到 .video 也垂直居中!请参阅以下示例:

body {
  height:100%;
  width:100%;
}
#frame {
  border:1px dotted red;
  display: flex;
  align-items: center;
  justify-content: center;
  height:200px;
}
.video {
  border:1px dotted blue;
  line-height:0;
  width: 80%;
}
<div id="frame">
  <div class="video">
    <img src="https://placehold.it/100x75"/>
  </div>
</div>

关于html - 为什么 Flexbox 不垂直居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43515744/

相关文章:

html - 子 Div 未拉伸(stretch)以垂直适应浏览器窗口的内容。

javascript - 本地主机上的循环变量设置,而不是实时站点上的循环变量设置

javascript - 在javascript中动态创建id

jquery - 单击 <a> 标签更改 <li> 的背景图像

CSS Grid 自动调整每行的宽度

css - 如何在 bool 玛级别组件中实现分词并设置左右等宽?

html - 嵌套的 flexbox 对齐元素中心特定内容

css - 我如何用 sass 简化这个 css?

jquery - 以两行显示电子邮件 ID

react-native - React Native - 带有内联文本的 hitSlop 的内联可压组件