Absolutely positioned div with zIndex -1 is hidden by Parent's children background-color

Viewed 23

I am attempting to absolutely position an image on top of a parent div. The image has been given a negative zIndex (zIndex: -1) in order to simulate a background image (it has to be this way). This parent div contains two child divs with two separate background-colors. I have tried giving the parent container a zIndex, but the image is still being hidden behind the children's background colors. My desired result is an absolutely positioned image that maintains a -zIndex that is not hidden behind the background colors of the child divs. Keep in mind, if there is text in the child divs I don't want the image to cover that text. My code is as follows:

    <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>
2 Answers

your image is on the third child? not the parent!

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>

I don't know if this is what you need. I converted your code to pure HTML/CSS.

  1. First, I closed the div with the image and instead of an image I used a yellow background to visualize it.
  2. I changed its z-index to 1 to be on the top of the other divs.

<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>

Related