0

I have 2 div elements with background-color set overlaying on top of another div with content. In case-1 overlay is not a sibling of the content div so it allow background text to be visible to user. In case-2 the overlay is a sibling of the content div so it is not showing the text to user.

Case-1

<div class="overlay"></div>
<div class="example-container">
  <div class="child1">
    Case 1 - Sample Text 1
  </div>
</div>

Case-2

<div class="child1">
  Case 2 - Sample text 2
</div>
 <div class="overlay">
 </div>

Sample JSfiddle to simulate 2 scenarios.

Any idea why this behavior in html? How could we make the overlay div with background color (case-2) always allow text transparency.

Praveen.R
  • 3
  • 2
  • just add `position:relative` on `.child1` and place the `overlay` before the `child1` or set `z-index: 1` on `child1` – Cornel Raiu Nov 21 '21 at 01:16
  • Does this answer your question? [how to use z-index with relative positioning?](https://stackoverflow.com/questions/8986071/how-to-use-z-index-with-relative-positioning) or [this](https://stackoverflow.com/questions/44597709/css-absolute-positioning-z-index) – Cornel Raiu Nov 21 '21 at 01:17

2 Answers2

0

The issue here is that the div is being rendered over the text. This can be fixed easily by giving the overlay a z-index property of -1. This makes the div render under the text, allowing you to see it.

example overlay css

.overlay {
    position: absolute; 
    background-color: gray;
    top:0;
    left:0;
    width: 100px;
    height: 100px;
    z-index: -1;
  }

Alternatively since you want it to overlay (if you actually don't that is a very misleading name) just set the opacity lower

.overlay {
    position: absolute; 
    background-color: gray;
    top:0;
    left:0;
    width: 100px;
    height: 100px;
    opacity: 0.5;
  }
 
Big Dumb
  • 120
  • 1
  • 7
0

Setting the position property for all siblings make this work.

I found this article very helpful, it explains various scenarios. https://coder-coder.com/z-index-isnt-working/

A sample fiddle that works. https://jsfiddle.net/praveenr/ukpw63hc/

Praveen.R
  • 3
  • 2