带opacity属性的重叠Div未按z-index预期显示的问题求助
问题描述
I can't for the life of me figure out why the higher z-index element is transparent where overlapped. Any ideas what im doing wrong here?
相关代码
.container { position: relative; width: 700px; height: 500px; border: 1px solid #ccc; overflow: hidden; position: relative; } .img1 { background: url('https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg'); background-size: cover; width: 300px; height: 200px; top: 50px; position: absolute; z-index: 3; opacity: 0.3; } .img2 { background: url('https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg'); background-size: cover; width: 300px; height: 200px; top: 150px: left: 200px; position: absolute; z-index: 1; opacity: 0.3; }
问题分析 & 解决方案
嘿,我帮你瞅了下代码,发现几个关键问题:
CSS语法错误导致定位失效
你看.img2里的top: 150px: left: 200px;,这里把分号写成冒号了!这直接导致left属性没生效,.img2压根没跑到你想要的位置,先把这个语法错误改过来:top: 150px; left: 200px;,这样两个元素才能正确重叠。透明度叠加导致视觉上的“更透明”
两个元素都设置了opacity: 0.3,当高z-index的.img1盖在.img2上面时,重叠区域是两层半透明叠加的效果——上层的0.3透明度会透出下层的0.3,视觉上就会比单个元素更淡,看起来像是上层在重叠处变透明了,但这其实是正常的透明度叠加逻辑。如果你不想让重叠区域有这种叠加效果,可以换个方式实现背景图的半透明,比如用伪元素来承载背景图和透明度,而不是给元素本身加
opacity:.img1 { width: 300px; height: 200px; top: 50px; position: absolute; z-index: 3; /* 去掉元素本身的opacity */ } .img1::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: url('https://letsenhance.io/static/8f5e523ee6b2479e26ecc91b9c25261e/1015f/MainAfter.jpg'); background-size: cover; opacity: 0.3; z-index: -1; /* 让伪元素在元素下方,不影响内容 */ }这样元素本身没有
opacity,不会创建额外的堆叠上下文,重叠区域只会显示上层伪元素的半透明,不会和下层的透明度叠加。
另外补充个小知识点:当元素设置opacity < 1时,会自动创建一个新的堆叠上下文,不过在这个例子里两个元素都在同一个父级堆叠上下文里,z-index的层级是没问题的,主要还是语法错误和透明度叠加的问题~
备注:内容来源于stack exchange,提问作者KingKongFrog

