【问题标题】:Why doesn't `width:100%; height:100%; object-fit: contain;` make a <video> fit its container?为什么不 `width:100%;高度:100%; object-fit: contains;` 使 <video> 适合其容器?
【发布时间】:2022-01-21 08:57:47
【问题描述】:

所以我有一个网格布局的页面,有页眉和页脚,中间有一个黑色内容容器。

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  height: 100%;
  grid-template-rows: max-content 1fr max-content;
}

.container div {
  border: 1px solid red;
}

.videoContainer {
  background-color: black;
}

video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<div class="container">
  <div>This is the header</div>
  <div class="videoContainer">
  </div>
  <div>This is the footer</div>
</div>

到目前为止一切顺利。

现在我想放一个可以拉伸以适应这个容器(并居中)的视频。这是object-fit: contain;的尝试

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  height: 100%;
  grid-template-rows: max-content 1fr max-content;
}

.container div {
  border: 1px solid red;
}

.videoContainer {
  background-color: black;
}

video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<div class="container">
  <div>This is the header</div>
  <div class="videoContainer">
    <video width="400" controls>
      <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    </video>
  </div>
  <div>This is the footer</div>
</div>

但它不起作用。容器会扩展以适应视频,而不是使视频适合容器。

如何使容器保持其固有尺寸并使视频适合其容器?

【问题讨论】:

  • 你从来没有给你的videoContainer任何max-heightheight
  • @YongPin 是来自grid-template-rows1fr,所以它应该是页面中间页眉和页脚之间的所有内容。但即使我给.videoContainer 一个height: 100% 问题是一样的。
  • 首先你需要知道1fr 等同于minmax(auto, 1fr),这意味着默认情况下容器不会小于其内容。因此,首先将1fr 替换为minmax(0, 1fr)。这将解决溢出问题。 revised demo | more details
  • 将单位更改为静态的,例如90vh
  • @MichaelBenjamin 啊哈!谢谢,您可以将其发布为答案吗?

标签: html css video css-grid object-fit


【解决方案1】:

1fr

首先你需要知道1fr 等同于minmax(auto, 1fr),这意味着默认情况下容器不会小于其内容。

所以,首先将1fr 替换为minmax(0, 1fr)。这将解决溢出问题。

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  height: 100%;
  grid-template-rows: max-content minmax(0, 1fr) max-content;
}

.container div {
  border: 1px solid red;
}

.videoContainer {
  background-color: black;
}

video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<div class="container">
  <div>This is the header</div>
  <div class="videoContainer">
    <video width="400" controls>
      <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    </video>
  </div>
  <div>This is the footer</div>
</div>

object-fit

如果您希望视频真正“适合此容器”(如覆盖整个宽度和高度),请尝试 object-fit: cover 而不是 contain

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2010-09-24
    • 2022-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多