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

absolute定位div被fixed定位div遮挡,如何实现完整显示?

解决fixed容器内absolute元素被其他fixed元素遮挡的问题

问题分析

你的代码里,两个fixed定位的div中,后出现的.fixed2默认堆叠层级更高,会盖住前面.fixed1里的所有元素——包括那个absolute定位的绿色盒子。这是因为fixed定位会创建独立的堆叠上下文,DOM顺序靠后的fixed元素默认优先级更高。

解决方案

给.fixed1设置更高的z-index值,让它的整个堆叠上下文层级超过.fixed2,这样内部的absolute元素自然会跟着显示在上方。

修改后的完整代码:

CSS

.fixed1 {
  position: fixed;
  top: 0;
  left: 100px;
  width: 100px;
  height: 100px;
  background-color: yellow;
  z-index: 1; /* 添加这行,提升堆叠层级 */
}
.fixed2 {
  position: fixed;
  top: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: red;
}
.relative {
  margin-top: 25px;
  width: 50px;
  height: 50px;
  background-color: blue;
}
.absolute {
  position: absolute;
  left: -25px;
  width: 50px;
  height: 50px;
  background-color: green;
}

HTML

<html>
  <div class="fixed1">
    <div class="relative">
      <div class="absolute"></div>
    </div>
  </div>
  <div class="fixed2">
    fixed1
  </div>
</html>

原理说明

fixed定位元素的堆叠层级由z-index控制,默认值为auto(相当于0)。给.fixed1设置z-index: 1后,它的堆叠优先级会高于.fixed2,其内部所有子元素都会继承这个堆叠上下文,不会被.fixed2遮挡,同时还能保持原有的absolute定位规则(相对于父级.relative定位)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:35:18