relativeの入れ子構造でz-indexの扱い
relativeがネストした構造
例えば疑似要素:afterでposition:absoluteしてz-indexを-1として影を付けた場合、
これ単体では正常に動くが、その要素の中でさらに同じように疑似要素:afterでposition:absoluteしてz-indexを-1として影を付けようとすると、中の疑似要素が何故か親要素の疑似要素と同じ階層になってしまう。
理由は、relativeが連続していて、新たなスタックコンテキストが生成されておらず、
親と同じスタック コンテキスト内になっているからです。
かといって、親の方でz-indexを設定すると新たなスタックコンテキストは生成できるが、afterで親要素の背後に要素を配置することができなくなってしまう.....。
<html> <head></head> <body> <style> .base{ position : relative; background : yellow; width : 200px; height : 400px; } .base:after{ content : ""; position : absolute; background : blue; z-index : -1; width : 200px; height : 400px; top : 20px; left : 20px; } .inner{ position : relative; background : red; width : 200px; height : 50px; margin-left : 20px; margin-top : 20px; } .inner:after{ content : ""; position : absolute; background : green; z-index : -1; width : 250px; height : 50px; top : 20px; left : 20px } </style> <div class="base">外側のDIV <div class="inner">内側DIV</div> </div> </body> </html>
結論としては以下のようにrelativeを連続させないで一段
divを挟みz-index:0で新たなスタックコンテキストは生成することで回避することができます。
<html> <head></head> <body> <style> .base{ position : relative; background : yellow; width : 200px; height : 400px; } .base:after{ content : ""; position : absolute; background : blue; z-index : -1; width : 200px; height : 400px; top : 20px; left : 20px; } .inner{ position : relative; background : red; width : 200px; height : 50px; margin-left : 20px; margin-top : 20px; } .inner:after{ content : ""; position : absolute; background : green; z-index : -1; width : 250px; height : 50px; top : 20px; left : 20px } </style> <div class="base">外側のDIV <div style="position:relative;z-index:0"> <div class="inner">内側DIV</div> </div> </div> </body> </html>