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

包含视频的Div始终置于顶层问题(CSS+HTML)

问题

我在重叠video元素时遇到问题:我有一个包含视频的div,尽管为下方的#content div设置了更高的z-index值,期望它显示在视频上方,但它始终处于视频下方,不清楚问题所在?

我原本以为设置z-index能让#content div显示在视频容器上方,但并未生效。

代码如下:

<style>

body{
    margin:0;
}

.video-container {
    z-index: 0;
    width: 100%;
    height:600px;
    position: relative;
}

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 1;
}

.video-container .caption {
  z-index: 2;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}

#content {
    z-index: 3;
    background-color:#0F6;
    padding:100px;
    margin: -100px 20% 100px 20%;
}

</style>
</head>

<body>

<div class="video-container">
    <video autoplay muted loop>
        <source src="Westgress Video.mp4" type="video/mp4" />
    </video>
    <div class="caption">
      <h2>Your caption here</h2>
    </div>
</div>



<div id="content">
  <h1>Content for  id "content" Goes Here</h1>
  <p>djfghkjdf</p>
  <p>kdfjhgkjdfdfgbdhfjghkjdfghjkdfhgkj</p>
  <p>kjdfbgkjdfghkjdfghkjdfhgkjdfkjg</p>
  <p>dfkjbhkjdfg</p>
</div>

</body>
</html>

解决方案

问题核心是:z-index只对非static定位的元素生效。你的#content默认是position: static,所以设置的z-index完全不起作用,自然没法覆盖视频容器。

只需要给#content添加position: relative(或者absolute、fixed这类非static值),z-index就能正常发挥作用了:

#content {
    z-index: 3;
    position: relative; /* 新增这一行 */
    background-color:#0F6;
    padding:100px;
    margin: -100px 20% 100px 20%;
}

额外说明:.video-container设置了position: relative,会创建独立的堆叠上下文,但#content不在这个容器内部,只要给#content加上非static定位,它的z-index层级就能高于视频容器,实现你要的覆盖效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:52:19