我试图让HTML5视频在不使用JS的情况下像background: center center fixed; background-size: cover;
元素一样运行(我知道那里有JS库可以做到这一点)。我想出了如何使用媒体查询(下面的示例假设您使用的是 16/9 视频)根据窗口的纵横比与视频的纵横比将宽度或高度设置为 100%)。我现在要做的就是让视频水平或垂直居中。
任何帮助将不胜感激。
@media screen and (max-aspect-ratio: 16/9) {
div#fixed video {
position: absolute;
height: 100%;
z-index: -100;
}
}
@media screen and (min-aspect-ratio: 16/9) {
div#fixed video {
position: absolute;
width: 100%;
z-index: -100;
}
}
@media screen and (max-aspect-ratio: 16/9) {
div#fixed video {
position: absolute;
height: 100%;
z-index: -100;
top: 0;
bottom: 0;
margin:auto 0;
}
}
@media screen and (min-aspect-ratio: 16/9) {
div#fixed video {
position: absolute;
width: 100%;
z-index: -100;
text-align: left;
right: 0;
left: 0;
margin:0 auto;
}
}
您甚至不需要媒体查询即可实现该:)
试试这个:
#fixed {
position: relative;
height: 100vh;
z-index: 0;
}
#fixed video {
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
-o-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
position: absolute;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
}
<div id="fixed">
<video autoplay loop class="bg-video">
<source src="https://d2v9y0dukr6mq2.cloudfront.net/video/preview/abstract-rainbow_wjpctkdes__PM.mp4" type="video/mp4">
</video>
</div>
这是一个工作的小提琴示例。
希望对:)有所帮助