0

Consider the following example that renders a semi-transparent red layer onto some text.

<div style="position: relative">
  <p>
    Foo
  </p>
  <p>
    Bar
  </p>
  <div style="position: absolute; left: 0; top: 0; bottom: 0; right: 0; background: rgba(255,0,0,0.5)">
  </div>
</div>

There are some issues on iOS Safari that makes using relative-divs in scrolling areas flaky.

So, is there a way to achieve the same effect of overlaying without using relative divs? CSS only, no JavaScript!

EDIT:

The actual effect I want to achieve is to change the overlay into a different color when the mouse hovers.

EDIT:

Looks like the "flakiness" is still present in current iOS versions. Here are some OLDER references to similar problems:

user3612643
  • 5,096
  • 7
  • 34
  • 55

1 Answers1

1

You can consider the background on the main element and make the child element behind.

.box {
  background: rgba(255, 0, 0, 0.5);
}

.box>* {
  position: relative;
  z-index: -1;
}

.box:hover {
  background: rgba(255, 0, 0, 0.8);
}
<div class="box">
  <p>
    Foo
  </p>
  <p>
    Bar
  </p>
</div>

Simply make sure there is no property used on the main element that will create a stacking context. Related: Why can't an element with a z-index value cover its child?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Looks great. The child is using relative, let's see if I still see the flakiness in iOS Safari with this approach. – user3612643 Feb 29 '20 at 10:02
  • I added a remark about hovering to my question. Could you please amend your answer and add ".box:hover {background: rgba(255, 0, 0, 0.8);}" to it. That shows the effect and works perfectly! Many thanks! – user3612643 Feb 29 '20 at 10:15
  • I now carefully checked on iOS Safari. The elements still randomly disappear as soon I introduce "relative" somewhere in the tree... – user3612643 Feb 29 '20 at 10:46