设置zIndex:-1的绝对定位div被父元素子元素背景遮挡问题
问题解决:z-index:-1的背景图不被子元素背景遮挡且不覆盖文本
问题场景
我需要把一张绝对定位的图片放在父div上方,为模拟背景图效果给图片所在div设置了zIndex:-1(必须保留这个设置)。父div里有两个带不同背景色的子div,已经给父容器设了zIndex,但图片还是被子元素的背景挡住了。想要实现:保持zIndex:-1的绝对定位图片不被子元素背景遮挡,同时不覆盖子div里的文本。
原代码
<div style={{ positon: "relative", zIndex: 0 }}> <div style={{ backgroundColor: "red", height: 500, width: "100%" }}>TEXT</div> <div style={{ backgroundColor: "blue", height: 500, width: "100%" }} >TEXT</div> <div style={{ backgroundRepeat: "no-repeat", backgroundPosition: "cover", backgroundImage: `url(${Squiggle1})`, height: 600, width: 451, position: "absolute", top: 250, bottom: 0, right: 0, zIndex: -1 }} /> </div>
解决方案
- 修正父容器拼写错误:把
positon改成position,否则父容器的相对定位不生效,z-index的层级计算会完全混乱。 - 调整子div层级规则:给两个带背景色的子div添加
position: relative和z-index: 1。这样子div的背景层会处于父容器层级之上,而图片的z-index:-1会在父容器层级之下;同时子div的文本会默认显示在自身背景层之上,不会被图片或背景色遮挡。
修改后的代码
<div style={{ position: "relative", zIndex: 0 }}> <div style={{ backgroundColor: "red", height: 500, width: "100%", position: "relative", zIndex: 1 }}>TEXT</div> <div style={{ backgroundColor: "blue", height: 500, width: "100%", position: "relative", zIndex: 1 }} >TEXT</div> <div style={{ backgroundRepeat: "no-repeat", backgroundPosition: "cover", backgroundImage: `url(${Squiggle1})`, height: 600, width: 451, position: "absolute", top: 250, bottom: 0, right: 0, zIndex: -1 }} /> </div>
原理说明
- 父容器设置
position: relative后,既成为绝对定位元素的参考容器,也建立了一个新的堆叠上下文。 - 子div设置
position: relative和z-index:1后,会在父容器的堆叠上下文里形成更高层级,它们的背景色会覆盖图片(因为图片z-index:-1处于父容器层级之下);而文本作为子div的内容,默认层级高于自身背景色,所以能正常显示在最上层。
内容的提问来源于stack exchange,提问作者Rob Terrell
相关产品推荐
相关产品推荐

