在没有高度但有填充的元素中垂直居中内容

Vertically centering content in an element with no height, but padding

Fiddle: http://jsfiddle.net/dbwvx42s

问题描述: 我正在使用 Bootstrap 在一个部分中创建一些列。该部分的高度为零(例如 height: 0),但底部填充为 56.25%,以保持页面上其他内容的纵横比 (16:9)。

我 运行 遇到的问题是如何在这个零高度填充元素中垂直居中内容。我尝试过 flexbox 解决方案但无济于事。我试过内联阻塞内容并使用垂直对齐,这也是不行的。我 运行 没戏了!

感谢任何帮助。

代码:

#section-1 {
    background-color: #0099cc;
    color: #fff;
    height: 0;
    padding-bottom: 56.25%;
}

您可以创建包含以下内容的绝对定位子元素:

#section-1 {
  
  position: relative;
  
  background-color: #0099cc;
  color: #fff;
  height: 0;
  padding-bottom: 56.25%;
}

#section-1 div.content {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  
}
<div id="section-1">
  <div class="content">
    Content goes here  
  </div>
</div>

现在,div.content 可以用作正常大小的 div。