使用纯CSS将具有固定宽高比的框中的内容垂直居中?

时间:2015-01-08 23:01:40

标签: html css html5 css3 vertical-alignment

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

  • 具有固定纵横比(16:9)的流体尺寸盒
  • 盒子里面有50%黑色覆盖层
  • 在叠加层顶部垂直居中的任意内容

我结合了我发现的几种技术:

到达与目标非常接近的东西:

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

在1280像素宽的视口中看起来很棒,但是如果你将浏览器拉得更窄或更宽,你会看到.overlay保持固定的高度而.container在保持稳定的高度保持16:9的宽高比。

如果我可以将第20行的值设置为100%,从而.overlay扩展到.container的视觉高度,那我就是金色的。可以理解为什么这样做不起作用(.container的实际高度为0),但我对接下来要尝试的内容感到难过。

请记住,我可能会认为这一切都是错误的,并且可能有一种完全不同的方法可以更好地运作。最终,对我来说最重要的是:

  • 跨浏览器支持回IE10
  • 仅限HTML / CSS(因为我可以在现有的基础上添加一些JS并使其运行良好)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

实际上有couple of ways来实现垂直对齐,但是我不会改变整个事情。

您只需定位.overlay元素absolute并通过向其width height 100%扩展其尺寸,以便它可以填充其父级.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>