position: absolute已设置但z-index仍不生效?展示图遮罩层与文字层级叠加问题排查
问题排查与解决方案
让我来帮你找出问题所在并解决它,你的代码里有两个关键问题导致z-index不生效以及遮罩效果异常:
1. 父元素未建立堆叠上下文,z-index无法生效
z-index属性只对非static定位的元素生效,你的#showcase默认是position: static,所以设置z-index:1完全不起作用。同时,伪元素#showcase::after使用了position:absolute,但因为父元素没有设置position: relative,它的定位是相对于整个视口,而不是#showcase——这就是你不得不硬编码top:68px的原因,既不灵活还容易出错。
2. 伪元素的堆叠顺序覆盖了文字内容
伪元素::after是#showcase的生成子元素,默认情况下它会和.container里的文字处于同一堆叠层级,而且因为伪元素是后插入的,会直接覆盖文字内容。
修正后的CSS代码
.container{ width:80%; margin: auto; overflow: hidden; } header{ background-color: #35424a; color: #fff; min-height: 45px; padding-top: 20px; border-bottom: 3px solid coral; } header ul{ margin:0; padding:0; } header li{ display: inline; list-style: none; padding:0 15px 0 15px ; } header h2{ float: left; } header nav{ float:right; } header h2{ margin: 0; } .coral{ color:coral; } #showcase{ background-image: url("images/showcase2.jpg"); background-position: center right; min-height: 300px; text-align: center; color: #fff; position: relative; /* 关键:建立堆叠上下文,让伪元素相对它定位 */ } #showcase::after { content: ""; position: absolute; top:0; /* 相对于#showcase顶部 */ left:0; /* 相对于#showcase左侧 */ width: 100%; height: 100%; /* 用100%代替硬编码300px,自适应高度 */ background-color: rgba(78, 89, 107, 0.6); z-index: 0; /* 让伪元素在文字下方 */ } #showcase .container{ position: relative; /* 让容器建立堆叠上下文 */ z-index: 1; /* 让文字在遮罩层上方 */ }
简化写法(可选)
你也可以把伪元素的z-index设为-1,这样不需要给.container额外设置z-index——伪元素会自动处于#showcase的背景之上、内容之下:
#showcase::after { content: ""; position: absolute; top:0; left:0; width: 100%; height: 100%; background-color: rgba(78, 89, 107, 0.6); z-index: -1; /* 伪元素在#showcase内容下方 */ }
内容的提问来源于stack exchange,提问作者nitish jha
相关产品推荐
相关产品推荐

