You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态调整背景视频高度以适配内容(无需保持宽高比)

解决方案

核心问题分析

你之前的文本容器用了absolute定位,它不会占据文档流空间,导致父容器的高度仅由py-16内边距决定,和文本内容高度无关。小屏幕下文本变高时,父容器和视频的高度自然不会同步变化。

方案一:纯CSS实现(推荐)

通过调整文本容器的定位方式,让它撑开父容器高度,同时视频作为绝对定位背景铺满父容器:

<div className="relative py-16">
  <!-- 背景视频:绝对定位铺满父容器 -->
  <video className="absolute inset-0 w-full h-full object-fill" autoPlay loop muted playsInline>
    <source src="/back_video.mp4" type="video/mp4" />
  </video>
  <!-- 文本容器:相对定位,占据文档流撑开父容器 -->
  <div className="relative z-10 mx-4 md:mx-16 mt-32 md:mt-0">
      <!-- faqs内容 -->
  </div>
</div>

关键样式说明:

  • inset-0:等价于top:0; right:0; bottom:0; left:0,让视频完全覆盖父容器
  • object-fill:强制视频拉伸填充容器,不保留原宽高比,满足你的需求
  • 文本容器改用relative z-10:既保证在视频上方,又能占据文档流空间,让父容器高度随文本内容自动变化

方案二:JavaScript兜底(特殊布局需求时用)

如果必须保留文本容器的absolute定位,可通过JS监听文本高度变化,同步设置父容器和视频的高度:

// 获取元素
const parentContainer = document.querySelector('.relative.py-16');
const textContainer = parentContainer.querySelector('.absolute.z-10');
const backgroundVideo = parentContainer.querySelector('video');

// 同步高度的函数
function syncVideoHeight() {
  const textHeight = textContainer.offsetHeight;
  // 父容器高度设为文本高度加上上下内边距(py-16对应32px)
  parentContainer.style.height = `${textHeight + 32}px`;
  backgroundVideo.style.height = `${textHeight + 32}px`;
}

// 初始化时同步一次
syncVideoHeight();
// 监听窗口 resize 事件,小屏幕切换时重新同步
window.addEventListener('resize', syncVideoHeight);

内容的提问来源于stack exchange,提问作者Chaser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:33:33