html - 使用视频作为 div 的背景

标签 html css html5-video

我想在 CSS3 中使用视频作为背景。我知道没有 background-video 属性,但是否可以执行此操作。使用全尺寸视频标签不会产生想要的结果,因为有些内容需要在视频上显示。

必须是非JS。如果不可能,那么我需要在我的服务器端进行更改,并提供结果以及视频的屏幕截图。

我需要视频来替换彩色框:

Boxes

彩色框只是 atm,CSS 框。

最佳答案

纯CSS方法

使用 object 可以将视频置于元素内,就像 cover 大小的 background-image without JS -fit 属性或 CSS 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/

相关文章:

javascript - 从文件中单独检索 HTML5 视频持续时间

php - 将ms word数据存入mysql

javascript - 如何使用 JavaScript 将 HTML 页面链接到其他地方

html - ul li li 删除 :before :after in second level.

html - 挣扎于 CSS 中的布局

html - 为什么网页显示水平滚动条,即使它适合屏幕

javascript - HTML5 视频 - 设置 video.currentTime 会破坏播放器

javascript - 自动向下滚动,但当用户滚动时停止

javascript - 如何将 div 元素移动到另一个 div 元素内?

video-streaming - 在Ubuntu上为WebRTC安装TURN服务器