我想在 CSS3 中使用视频作为背景。我知道没有 background-video 属性,但是否可以执行此操作。使用全尺寸视频标签不会产生想要的结果,因为有些内容需要在视频上显示。
必须是非JS。如果不可能,那么我需要在我的服务器端进行更改,并提供结果以及视频的屏幕截图。
我需要视频来替换彩色框:
彩色框只是 atm,CSS 框。
最佳答案
纯CSS方法
使用 object 可以将视频置于元素内,就像
属性或 cover
大小的 background-image
without JS -fitCSS Transforms
。
2021 答案:对象匹配
正如评论中所指出的,无需 CSS transform
,但使用 object-fit
也可以获得相同的结果,我认为这是一个更好的选择同样的结果:
.video-container {
height: 300px;
width: 300px;
position: relative;
}
.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
上一个答案:CSS 转换
借助 transform
CSS 属性,您可以轻松地将视频设置为任何 HTML 元素的背景。
请注意,您可以使用transform
技术将任何 HTML 元素垂直和水平居中。
.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}
.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
关于html - 使用视频作为 div 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20818881/