首页 > 解决方案 > 将视频设置为 div 背景并将文本放在前面

问题描述

我想将我的文本背景设置为视频。在我尝试后,我无法将文本放在前面。文字总是隐藏在背后。另一个问题是视频背景在较小的屏幕上没有响应,它覆盖了整个屏幕。更重要的是,似乎视频的帧宽度和高度已被删除(例如,不以原始宽度和高度比播放)。

谁能帮我解决这个问题?

HTML:

<div class="container-fluid no-left-padding no-right-padding welcome-text video-content">
   <!-- Container -->
   <div class="container">
      <video autoplay muted loop>
         <source src="assets/videos/welcome_video.mp4" type="video/mp4">
      </video>
      <h2>Hello, I want to display this text, and play the video on background.
      </h2>
   </div>
</div>

CSS:

.welcome-text {
    padding-bottom: 180px;
    padding-top: 180px;

}
.video-content{
    height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
}
video{
    min-width: 100%;
    min-height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

标签: htmlcssbootstrap-4html5-videocss-transitions

解决方案


在视频前面带上文字:

.welcome-text {
    position: relative;
    /* make it position:absolute instead if you want it to be centered as shown below*/
    z-index: 1;
}

容器中的中心文本:

.container {
    position: relative;
}

.welcome-text {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

关于使视频响应并保持纵横比,您必须弄清楚纵横比是多少。假设视频为 1280 x 720,则纵横比为 1.78:1。这意味着如果宽度为 100%,则高度应为 56%。

你不能告诉 div 有 56% 的容器宽度,但是有一个技巧,你可以告诉它有 56% 的宽度作为填充:

.container {
    position: relative;
    height: 0;
    padding-bottom: 56%;
    overflow: hidden;
}

video {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}

推荐阅读