![](/img/trans.png)
[英]What is the difference between "object-fit: contain" and "max-width: 100%;max-height:100%"?
[英]Why doesn't `width:100%; height:100%; object-fit: contain;` make a <video> fit its container?
所以我有一個網格布局的頁面,中間有一個 header 和一個頁腳和一個黑色內容容器。
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>
但它不起作用。 容器擴展以適應視頻,而不是使視頻適合容器。
如何將容器保持在其固有尺寸並使視頻適合其容器?
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.