设置定位后Header的Z-index仍不生效问题求助
问题
我有一个简单的React组件,包含一个用于header的div和一个用于页面其余部分的div。header的div设置为fixed定位,主体div设置为relative定位。我将header的z-index设置为高于主体,但它仍然被覆盖,我不确定原因。
JSX代码
<div id="host"> <div className="header"> </div> <div className="container-top body"> <h1>Start a Game</h1> <p> Select a Game Below or{" "} <Link id="create-game-link" to="/create-quiz"> Create your Own! </Link> </p> {renderAction()} </div> </div>
CSS代码
.container-top { display: flex; flex-direction: column; align-items: center; } .header { position: fixed; width: 100%; height: 50px; z-index: 5; border-bottom: 1px solid #3a5a40; box-shadow: 5px 2px 5px #333333; } .body { position: relative; top: 70px; height: 2000px; }
解决方案
这个问题基本是堆叠上下文导致的,按下面几个方向排查修复:
检查父容器
#host有没有设置z-index、transform、opacity < 1、filter这类属性——这些属性会创建独立的堆叠上下文,导致内部子元素的z-index只能在这个上下文里生效,没法突破到外部。如果有,直接移除这些属性就行。给
.body显式设置z-index值(比如z-index: 1),虽然relative定位元素默认z-index是auto,但显式声明能避免一些隐性的层级冲突。检查
.header是否缺了背景色。fixed定位元素如果没设置背景,会透出下方内容,看起来像是被覆盖,实则是背景透明。给.header加上background-color: #fff(或你需要的颜色)就能解决。
修改后的参考CSS:
.container-top { display: flex; flex-direction: column; align-items: center; } .header { position: fixed; width: 100%; height: 50px; z-index: 5; border-bottom: 1px solid #3a5a40; box-shadow: 5px 2px 5px #333333; background-color: white; /* 添加背景色 */ } .body { position: relative; top: 70px; height: 2000px; z-index: 1; /* 显式设置层级 */ }
内容的提问来源于stack exchange,提问作者Bruno Oliveira
相关产品推荐
相关产品推荐

