Elements with transparency appearing above an opaque foreground element.

When using some element transparency and overlay, we encounter CSS weirdness that we cannot solve.

http://i.imgur.com/h5Lzvde.png

As shown in the screenshot, there are two img elements with 0.4 opacity. Then we open the inscription on top of them, and they appear before it. When opacity is set to 1.0, they are no longer displayed in front.

Another relevant CSS is that the overlay has a Z-index of 999 and has no generic button connection.

+4
source share
1 answer

Opacity affects styling

Consider the following HTML snippet:

<div class="wrapper tweak"> <div class="overlay"> <p>The Overlay Panel</p> </div> <div class="content"> <p>The main Content panel with a motif: <b>&hearts;</b> <b class="foggy">&spades;</b></p> </div> </div> 

and the following CSS:

 .wrapper { position: relative; outline: 1px solid blue; } .overlay { position: absolute; top: 0; left: 0; background-color: white; border: 1px dotted blue; width: 400px; } .content pb { background-color: black; color: white; padding: 0 10px; opacity: 1.0; /* default value */ } .content p b.foggy { opacity: 0.4; } .tweak .overlay { z-index: 1; } 

Basically, I have a wrapper with two child .overlay , .overlay and .content . Note that the overlay is in front of the content in the code (DOM). If this happened, you would not see the problem in the first place.

The content contains two bold elements with two different opacity values.

See the main line in the demo script: http://jsfiddle.net/audetwebdesign/DxQZv/

When you enable the overlay, a .foggy element with an opacity of 0.4 appears before the label. The stacking order for this layout is from beginning to end: content in the stream with opacity 1.0 (default), absolutely positioned overlay, then an element with opacity 0.4.

However, if you explicitly set z-index: 1 to .overlay (add the .tweak class), then .overlay is placed higher in stacking order.

There are other ways to adjust the z-index value to get the same effect, but it might be the easiest.

Reference:

See 9.9.1 Specifying a Stack Level: The "z-index" Property in the CSS2 Specification
and 3.2. Transparency: The opacity property in the CSS3 color module specification.

Technically, adding an opacity value (other than 1.0) to an element creates a new stacking context with a z-index of 0, which also happens with a positioned element.

However, when two elements have the same z-index, they are painted in the order in which they appear in the DOM (tree order). In this case, the overlay is first applied, and then the bold element with an opacity of 0.4, so it appears before the overlay.

There is also an earlier question that addresses the same issue:

Which has a higher priority: opacity or z-index in browsers?

which I found after I posted my answer.

+6
source

Source: https://habr.com/ru/post/1485017/


All Articles