16:9的底部留白在火狐浏览器中无法按预期工作

7

我一直在尝试为内容块实现响应式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 Chrome - Imgur
FireFox FireFox - Imgur 颜色块只是为了帮助可视化不同的框。

你究竟想要做什么? - odedta
3个回答

10

您的示例中存在的问题是,应用于 .streamRatio 的顶部填充在Firefox中相对于.streamContainerheight计算,而在Chrome中相对于.streamRatiowidth计算(给出了您期望的结果)。

哪一个是正确的?实际上,这两种实现都是正确的:

弹性盒子布局模块中的百分比边距和填充可以针对以下任一解决:

  • 它们自己的轴(左/右百分比相对于宽度,上/下相对于高度),或者内联轴 (左/右/上/下百分比都相对于宽度)
  • 用户代理必须选择这两种行为之一。

CSS Flexible Box Layout Module Level 1 (Flex Item Margins and Paddings)

因此,W3C建议您不要在弹性项上使用基于百分比的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>


这正是我一直在寻找的,而且你甚至解释了原因!非常感谢!很高兴这只是部分地我的无能为力! - AstroDoge
很高兴能够帮助。在这种情况下,不要认为是你的错,规范允许浏览器实现行为的多种方式非常奇怪。 - Hidden Hobbes

6
.streamRatio 的填充移动到 ::before 伪元素上可以使其在 Firefox 和 Edge 上正确显示。
.streamRatio::before {
  display: block;
  content: '';
  padding: 56.25% 0 0 0;
}

这是一个很好的解决方案,感谢您! - Tomtids

0

在display:flex中,Firefox不接受百分比的padding。

我添加了

display:table;
padding-bottom:56.25%;

它解决了问题,尽管我不确定是否会带来其他问题。在测试IE、Chrome、Safari和Firefox时,我没有看到任何问题。至少在最近的版本中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接