所以我有一个带有网格布局的页面,带有页眉和页脚,中间有一个黑色内容容器。
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>
到目前为止一切顺利。
现在我想放置一个视频,该视频将拉伸(stretch)以适合该容器(并居中)。这是 object-fit: contains;
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>
但是这不起作用。容器不是将视频适合容器,而是扩展以适合视频。
如何使容器保持其固有尺寸并使视频适合其容器?
最佳答案
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: cover
而不是 contain
.
关于html - 为什么 `width:100%; height:100%; object-fit: contain;` 无法使 <video> 适合其容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70795059/