使用纯 CSS 在具有固定纵横比的框中垂直居中内容?

Vertically center content in a box with a fixed aspect ratio using pure CSS?

使用 HTML/CSS,我正在尝试创建以下内容:

我结合了一些我发现的技巧:

达到非常接近目标的结果:

http://codepen.io/troywarr/pen/zxNdKP?editors=110

这在 1280 像素宽的视口中看起来不错,但如果将浏览器拉窄或拉宽,您会看到 .overlay 保持固定高度,而 .container 流畅地调整大小,同时仍保持16:9 宽高比。

如果我可以将第 20 行的值设置为 100%,从而使 .overlay 扩展到 .container 的视觉高度,我会很高兴。可以理解为什么这不起作用(.container 的实际高度为 0),但我对下一步要尝试什么感到困惑。

请记住,我的做法可能全错了,可能有一种完全不同的方法效果更好。最后,对我来说重要的是:

感谢您的帮助!

其实有couple of ways可以实现垂直对齐,但是我不打算改变整个事情。

您只需将 .overlay 元素定位 absolutely 并通过给它一个 widthheight100% 来扩展它的维度,这样它就可以填充其父项的整个 space,即 .container:

Example Here

.container {
  /* other declarations... */
  padding-bottom: 56.25%;
  text-align: center;
  position: relative;
  overflow: hidden; /* arbitrary */
}

.overlay {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

还可以使用 vw viewport percentage length 以便 font-size 属性 根据视口大小进行更改。

body {
  font-family: 'Helvetica Neue', Helvetica, sans-serif;
  background-color: #59488b;
  -webkit-font-smoothing: antialiased;
  margin: 20px auto;
  width: 40%;
}

.container {
  background-image: url(http://lorempicsum.com/up/1080/1080/4);
  background-size: cover;
  background-position: 50%;
  margin: 0 auto;
  padding-bottom: 56.25%;
  text-align: center;
  position: relative;
  overflow: hidden; /* arbitrary */
}

.overlay {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.content {
  color: #fff;
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

h1 {
  margin: 0;
  font-size: 6vw;
}

p {
  margin: 0;
  font-size: 3vw;
}
<div class="container">
  <div class="overlay">
    <div class="content">
      <h1>Title</h1>
      <p>This is some text!</p>
    </div>
  </div>
</div>