带有 zIndex -1 的绝对定位 div 被父级的子级背景颜色隐藏



我试图将一个图像绝对定位在父div的顶部。为了模拟背景图像,该图像被赋予了负zIndex(zIndex:-1((必须是这样(。这个父div包含两个子div,它们有两种不同的背景颜色。我尝试给父容器一个zIndex,但图像仍然隐藏在子容器的背景色后面。我想要的结果是一个绝对定位的图像,它保持了一个-zIndex,它不会隐藏在子div的背景色后面。请记住,如果子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>

您的图像在第三个孩子身上?不是家长!

body {
font-family: sans-serif;
}
.one {
position: relative;
z-index: 1;
}
.two {
background-color: red;
height: 500px;
width: 100%;
}
.three {
background-color: blue;
height: 500px;
width: 100%;
}
.four {
background-repeat: no-repeat;
background-position: cover;
background-image: url("https://images.unsplash.com/photo-1663919009310-ecd1d054e09f?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw3fHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60");
height: 600px;
width: 451px;
position: absolute;
top: 250px;
bottom: 0;
right: 0;
z-index: 100;
}
<div class="one">
<div class="two"></div>
<div class="three"></div>
<div class="four" />
</div>

我不知道这是否是您所需要的。我将您的代码转换为纯HTML/CSS。

  1. 首先,我用图像关闭div,并使用黄色背景来可视化它,而不是图像
  2. 我将它的z索引更改为1,以便位于其他div的顶部

<div style="positon: relative; z-index: 0">
<div style="background-color: red; height: 500px; width: 100%; position:relative;z-index:-2">TEXT</div>
<div style="background-color:blue; height: 500px; width: 100%; position:relative;z-index:-2"></div>
<div style="background-color:yellow;height: 600px;width: 451px;position: absolute;top: 250px;bottom: 0;right: 0;z-index:-1"></div>
</div>

最新更新