JustCarlos
JustCarlos

Reputation: 128

Opacity effecting absolutely positioned element

I have two containers (container1 and container2) and in container1 I have a child element. This child element is absolutely positioned and half the element overlaps over container2. I understand if I add opacity to container1 all it's child elements inherent the property but if I add opacity to container2 it ends up effecting the child element of container1 even though container2 is not it's parent element. An explanation would be very helpful.

Here is the HTML code:

  <body>
    <div id="container1" style='height: 250px; background-color: red'>
      <div id="child" style="height: 290px; width: 200px; background-color: green; position: absolute; top: 100px; left: 30%"></div>
    </div>

    <div id="container2" style="height: 250px; background-color: purple; font-size: 130px; opacity: 0.5">Some really big text</div>
  </body>

Here is a screenshot of what's happening: https://i.sstatic.net/A84Li.png

Upvotes: 1

Views: 30

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4767

I think it is due to the green element being behind the purple element. Essentially, the purple <div> element is casting a purple tint over the green child <div>. When the opacity of container2 is set to anything other than, opacity:1 it seems to be causing child to be overlaid by container2. In this case setting the z-index will resolve the issue. Where the z-index will control the hierarchy outwards perpendicular to the xy-plane. Press the Run code snippet button below to see the results:

#container1 {
  height: 250px;
  background-color: red
}

#child {
  height: 290px;
  width: 200px;
  background-color: green;
  position: absolute;
  top: 100px;
  left: 30%;
  z-index: 1;
}

#container2 {
  height: 250px;
  background-color: purple;
  font-size: 130px;
  opacity: 0.2;
}
<body>
  <div id="container1">
    <div id="child"></div>
  </div>

  <div id="container2"></div>

</body>

Upvotes: 1

Related Questions