Bootstrap 5:如何正确设置Hero区域背景视频
问题描述
我有一个如下所示的模板效果:
我想把Hero区域的背景图换成背景视频,于是在section里添加了<video>标签,代码如下:
<!-- ======= Hero Section ======= --> <section id="hero" class="d-flex align-items-center"> <video autoplay muted loop id="myVideo"> <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4"> </video> <div class="container position-relative" data-aos="fade-up" data-aos-delay="500"> <h1>Welcome to Day</h1> <h2>We are team of talented designers making websites with Bootstrap</h2> <a href="#about" class="btn-get-started scrollto">Get Started</a> </div> </section><!-- End Hero -->
但视频导致下方的内容div被挤压,效果如下:
我还试过用CSS的background:url把视频设为背景,但视频加载失败:
#hero { width: 100%; height: calc(100vh - 110px); background: url("https://www.w3schools.com/howto/rain.mp4") top center; background-size: cover; position: relative; }
效果如下:
请问怎么正确加载背景视频,让欢迎消息div覆盖在视频上面而不是并排显示?
更新尝试
修改后的代码:
<!-- ======= Hero Section ======= --> <section id="hero" class="d-flex align-items-center"> <video autoplay muted loop id="myVideo"> <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4"> </video> <div class="container position-absolute" data-aos="fade-up" data-aos-delay="500"> <h1>Welcome to Day</h1> <h2>We are team of talented designers making websites with Bootstrap</h2> <a href="#about" class="btn-get-started scrollto">Get Started</a> </div> </section><!-- End Hero -->
效果如下:
解决方案
要实现视频作为Hero区域背景、内容层覆盖其上的效果,通过CSS对视频和内容容器做定位控制即可:
设置Hero容器为相对定位
把#hero设为相对定位,让内部绝对定位元素以此为基准,同时添加overflow: hidden防止视频超出容器范围:#hero { position: relative; width: 100%; height: calc(100vh - 110px); overflow: hidden; display: flex; align-items: center; }视频设为绝对定位,铺满容器
让视频作为背景层铺满整个Hero区域,并用z-index: -1将其压到内容层下方,同时用object-fit: cover保持视频比例避免拉伸变形:#myVideo { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; }内容容器保持相对定位
内容容器使用Bootstrap的position-relative类即可,确保它在视频上方正常显示:<div class="container position-relative" data-aos="fade-up" data-aos-delay="500"> <!-- 原有内容不变 --> </div>
完整可运行代码
<!-- ======= Hero Section ======= --> <section id="hero" class="d-flex align-items-center"> <video autoplay muted loop id="myVideo"> <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4"> </video> <div class="container position-relative" data-aos="fade-up" data-aos-delay="500"> <h1>Welcome to Day</h1> <h2>We are team of talented designers making websites with Bootstrap</h2> <a href="#about" class="btn-get-started scrollto">Get Started</a> </div> </section><!-- End Hero -->
#hero { position: relative; width: 100%; height: calc(100vh - 110px); overflow: hidden; display: flex; align-items: center; } #myVideo { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; }
这样设置后,视频会铺满Hero区域作为背景,内容层则正常显示在视频上方,不会出现挤压或错位问题。
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

