如何正确实现响应式视频背景并在其上居中显示标题?
响应式视频背景+居中文字实现方案
问题根源
原代码存在三个核心问题导致布局失效:
.home-content设置width:100vh,在移动端会触发横向溢出,破坏响应性- 视频使用
position:absolute但未给父容器.homeImage设置position:relative,导致视频脱离正常布局流,定位混乱 - 视频固定
height:100vh,无法随容器尺寸自适应
修改后的完整代码
HTML代码
<div className='homeImage'> <video loop autoPlay muted> <source src={video} type="video/mp4"/> </video> <div className='home-content'> <h1 className='mb-4'>My Name</h1> <h2>This is a blog</h2> </div> </div>
CSS代码
/* 父容器设置相对定位,作为绝对定位元素的参考基准 */ .homeImage{ background-color: black; position: relative; min-height: 100vh; /* 确保容器至少占满整个视口高度 */ display: flex; justify-content: center; align-items: center; text-align: center; } .home-content{ height: 100vh; width: 100%; /* 替换100vh宽度,避免移动端横向溢出 */ display: flex; justify-content: center; align-items: center; flex-direction: column; z-index: 10; /* 统一设置文字层级,无需单独给每个标题加 */ } .home-content h1{ font-size: 90px; color: #fff; margin-bottom: 1rem; } .home-content h2{ font-size: 40px; color: #fff; } .homeImage video{ opacity: 0.5; position: absolute; top: 0; left: 0; right: 0; bottom: 0; /* 让视频铺满整个父容器 */ width: 100%; height: 100%; object-fit: cover; /* 保持视频比例,避免拉伸变形 */ z-index: 0; } /* 移动端响应式调整 */ @media (max-width: 767px){ .home-content h1{ font-size: 60px; } .home-content h2{ font-size: 35px; } } @media (max-width: 497px){ .home-content h1{ font-size: 30px; } .home-content h2{ font-size: 20px; } }
核心修改说明
- 相对定位父容器:给
.homeImage添加position:relative,确保内部绝对定位的视频不会脱离布局流,始终以该容器为定位基准 - 自适应视频背景:用
top/left/right/bottom:0代替固定宽高,让视频自适应父容器尺寸,object-fit:cover保证视频比例正常显示 - 修复内容宽度:将
.home-content的width:100vh改为width:100%,彻底解决移动端横向滚动问题 - 简化层级管理:把文字的
z-index统一设置在.home-content上,代码更简洁易维护
内容的提问来源于stack exchange,提问作者user20984154
相关产品推荐
相关产品推荐

