如何实现背景图半透明且内容不遮挡?z-index失效问题求助
解决背景图片半透明且内容不被遮挡的问题
问题原因
你的代码里.content元素没有设置定位属性,z-index仅对position值为relative/absolute/fixed/sticky的元素生效,所以背景层(已设置absolute定位)会默认覆盖在未定位的内容层上方,导致文字无法选中。
解决方案1:给内容层添加定位属性
只需给.content加上position: relative,让z-index生效,即可将内容层置于背景层之上:
body { display: flex; height: 100vh; margin: 0; padding: 0; } .chat__body { position: relative; flex: 1; background: #efeae2; } .chat__body .background { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-image: url('https://www.rd.com/wp-content/uploads/2021/04/GettyImages-10100201-scaled.jpg'); background-size: contain; opacity: 0.4; z-index: 1; } .chat__body .content { position: relative; /* 添加定位属性 */ z-index: 2; }
HTML保持不变:
<div class='chat__body'> <div class='background'></div> <div class='content'> <p>Test</p> </div> </div>
解决方案2:使用伪元素简化结构
不需要额外的background标签,直接用父元素的伪元素实现背景,结构更简洁,也不会出现层级问题:
body { display: flex; height: 100vh; margin: 0; padding: 0; } .chat__body { position: relative; flex: 1; background: #efeae2; } /* 用伪元素生成背景层 */ .chat__body::before { content: ''; position: absolute; inset: 0; /* 等价于top/right/bottom/left: 0 */ background-image: url('https://www.rd.com/wp-content/uploads/2021/04/GettyImages-10100201-scaled.jpg'); background-size: contain; opacity: 0.4; z-index: 0; } .chat__body .content { position: relative; z-index: 1; /* 确保内容在背景之上 */ }
HTML简化为:
<div class='chat__body'> <div class='content'> <p>Test</p> </div> </div>
内容的提问来源于stack exchange,提问作者dokgu
相关产品推荐
相关产品推荐

