【问题标题】:Vertically center content in a box with a fixed aspect ratio using pure CSS?使用纯CSS在具有固定纵横比的框中垂直居中内容?
【发布时间】:2015-01-09 07:49:11
【问题描述】:
使用 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 并让它运行良好)
感谢您的帮助!
【问题讨论】:
标签:
html
css
vertical-alignment
【解决方案1】:
其实有couple of ways可以实现垂直对齐,但是我不打算改变整个事情。
您只需要定位.overlay 元素absolutely 并通过为其提供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>
【讨论】:
-
感谢哈希姆!这是朝着正确方向迈出的一步——看起来.overlay 现在与.container 的高度匹配。但是,我能做些什么来垂直居中内容呢?至少在 Chrome 中,它被压在盒子的顶部 (screenshot)。
-