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

如何用HTML和CSS在头部添加像素背景视频并在上方叠加文字

问题修复方案
    1. HTML结构错误:你错误将页面渲染内容放在了<head>标签内,<head>标签仅用于存放页面元数据、样式表引用等非渲染内容,所有可见内容必须放在<body>标签内,你这里的<head id="home">要改为普通容器标签比如<header id="home">。
    1. 视频资源路径错误:你填写的视频地址是本地文件名pexels-magda-ehlers-5306154.mp4&,末尾还多了无效的&字符,且没有使用Pexels提供的公网可访问的视频直链,导致线上环境无法加载到视频资源。
    1. 定位适配问题:当前视频用了position: fixed且高度设为100vh,会覆盖顶部导航栏,如果你要排除导航栏区域,需要根据导航栏实际高度调整视频的top和height属性。
    1. 层级问题:固定定位的视频默认层级可能高于后续内容,需要给.content设置z-index: 1保证叠加文字显示在视频上方,可根据需要给视频设置z-index: 0。

修复后HTML代码

<div class="all">
  <!-- 把原来的head改为header,head标签不能放可见渲染内容 -->
  <header id="home">
    <div id="welcome-section">
      <video autoplay muted loop id="myVideo">
        <!-- 这里替换为你从Pexels获取的完整公网mp4直链地址 -->
        <source src="替换为Pexels提供的完整mp4直链" type="video/mp4">
      </video>
      <div class="content">
        <h1>Hello</h1>
      </div>
    </div>
  </header>
  <!-- 后续meet the team等其他页面内容 -->
</div>

修复后CSS代码

html, .all {
  margin:0;
  height:100%;
  box-sizing:border-box;
  background-image: url("https://m.media-amazon.com/images/I/41g8yeF0NWL._AC_.jpg");
  background-repeat: no-repeat;
  background-size:cover;
  background-attachment: fixed;
}

#welcome-section{
  position: relative;
  overflow: hidden;
  width: 100%;
  font-size:50px;
  color:white;
  /* 如果你的导航栏高度为60px,就把高度改为 calc(100vh - 60px),同时设置margin-top: 60px */
  height: 100vh;
}

#myVideo {
  object-fit: cover;
  width: 100vw;
  /* 如果导航栏高度为60px,就把高度改为 calc(100vh - 60px),top改为60px */
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}

.content {
  position: relative;
  height: 100%;
  width: 100%;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

如果需要视频仅在头部区域显示不跟随页面滚动,保留上面代码里视频的position: absolute设置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:21:03