M-Pixel's solution 很棒,因为它解决了Timothy's answer 的缩放问题(视频会放大但不会缩小,所以如果你的视频真的很大,你很有可能只会看到部分放大它)。但是,该解决方案基于与视频容器大小相关的错误假设,即它必须是视口宽度和高度的 100%。我发现了一些对我不起作用的情况,所以我决定自己解决这个问题,我相信我想出了最终解决方案。
HTML
<div class="parent-container">
<div class="video-container">
<video width="1920" height="1080" preload="auto" autoplay loop>
<source src="video.mp4" type="video/mp4">
</video>
</div>
</div>
CSS
.parent-container {
/* any width or height */
position: relative;
overflow: hidden;
}
.video-container {
width: 100%;
min-height: 100%;
position: absolute;
left: 0px;
/* center vertically */
top: 50%;
-moz-transform: translate(0%, -50%);
-ms-transform: translate(0%, -50%);
-webkit-transform: translate(0%, -50%);
transform: translate(0%, -50%);
}
.video-container::before {
content: "";
display: block;
height: 0px;
padding-bottom: 56.25%; /* 100% * 9 / 16 */
}
.video-container video {
width: auto;
height: 100%;
position: absolute;
top: 0px;
/* center horizontally */
left: 50%;
-moz-transform: translate(-50%, 0%);
-ms-transform: translate(-50%, 0%);
-webkit-transform: translate(-50%, 0%);
transform: translate(-50%, 0%);
}
它也基于视频的比例,因此如果您的视频的比例不是 16 / 9,您将需要更改 padding-bottom %。除此之外,它开箱即用。在 IE9+、Safari 9.0.1、Chrome 46 和 Firefox 41 中测试。
编辑(2016 年 3 月 17 日)
自从我发布这个答案后,我编写了一个小的 CSS 模块来模拟 <video> 元素上的 background-size: cover 和 background-size: contain:http://codepen.io/benface/pen/NNdBMj
它支持视频的不同对齐方式(类似于background-position)。另请注意,contain 的实现并不完美。与background-size: contain 不同,如果容器的宽度和高度更大,它不会将视频缩放到超过其实际大小,但我认为它在某些情况下仍然有用。我还添加了特殊的fill-width 和fill-height 类,您可以将它们与contain 一起使用以获得contain 和cover 的特殊组合...试试吧,随时改进它!