我一直在尝试为内容 block 实现响应式 16:9 比例技巧,虽然在 Chrome 中获得了预期的结果,但其他浏览器(如 FireFox 和 Edge)的显示方式完全不同,并非预期。
.streamContainer {
position: absolute;
width: 80%;
height: calc(100% - 120px);
display: flex;
bottom: 0px;
flex-direction: column;
justify-content: center;
box-sizing: border-box;
transition: height 0.5s;
background: blue;
}
.streamRatio {
position: relative;
width: 100%;
padding: 56.25% 0 0 0;
content: '';
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
display: block;
background: red;
height: 0;
}
.streamInner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
background: green;
}<div class="streamContainer">
<div class="streamRatio">
<div class="streamInner">
Content Goes Here
</div>
</div>
</div>
下图显示了在 Chrome 上的预期结果和在 FireFox 上的意外结果:
Chrome - Imgur
FireFox - Imgur
颜色 block 只是为了帮助可视化不同的盒子。
最佳答案
您在示例中遇到的问题是,应用到 .streamRatio 的顶部填充是根据 .streamContainer 的 height 计算的> 在 Firefox 中,但在 Chrome 中反对 .streamRatio 的 width(给你你期望的结果)。
哪个是对的?好吧,事实证明这两种实现都是正确的:
Percentage margins and paddings on flex items can be resolved against either:
- their own axis (left/right percentages resolve against width,
- top/bottom resolve against height), or, the inline axis (left/right/top/bottom percentages all resolve against width)
A User Agent must choose one of these two behaviors.
CSS 灵活框布局模块级别 1 ( Flex Item Margins and Paddings )
出于这个原因,W3C 建议您不要在 flex 元素上使用基于百分比的 padding。
要解决这个问题,您需要删除 flexbox 功能并使用不同的方法垂直对齐容器,在这种情况下使用 top: 50%; 和 transform: translateY(-50%) ;:
.streamContainer {
background: blue;
bottom: 0;
box-sizing: border-box;
height: calc(100% - 120px);
position: absolute;
transition: height 0.5s;
width: 80%;
}
.streamRatio {
background: red;
box-sizing: border-box;
display: block;
height: 0;
padding: 56.25% 0 0 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
}
.streamInner {
background: green;
bottom: 0;
height: 100%;
left: 0;
right: 0;
position: absolute;
top: 0;
}<div class="streamContainer">
<div class="streamRatio">
<div class="streamInner">
Content Goes Here
</div>
</div>
</div>
关于html - 16 :9 padding-bottom trick not working as expected in FireFox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825787/