css - z-index when using ::after under element -


if use z-index combined position: absolute; possible place ::before of element under itself. there example on another question (jsfiddle.net/ldtfpvxy).

basically

<div id="element"></div>  #element {      position: relative;     width: 100px;     height: 100px;     background-color: blue; }  #element::after {     content: "";     width: 150px;     height: 150px;     background-color: red;      /* create new stacking context */     position: absolute;     z-index: -1;  /* below parent element */ } 

renders:

enter image description here

so stacking context/order defined z-index. when apply z-index: 1; element , z-index: -1; ::before cannot achieve same thing.

only if omit z-index element.

any ideas why is? element rendered after ::before & ::after pseudos same z-index?

working: https://jsfiddle.net/ldtfpvxy/
not working: https://jsfiddle.net/ldtfpvxy/1/ (only added z-index: 1; element)

your div , pseudo-child members of same stacking context, in case root stacking context. new stacking context give pseudo-element used reference children (which non-existant), z-index value applies current stacking context. , css spec dictates following paint order each stacking context:

within each stacking context, following layers painted in back-to-front order:

  1. the background , borders of element forming stacking context.
  2. the child stacking contexts negative stack levels (most negative first).
  3. the in-flow, non-inline-level, non-positioned descendants.
  4. the non-positioned floats.
  5. the in-flow, inline-level, non-positioned descendants, including inline tables , inline blocks.
  6. the child stacking contexts stack level 0 , positioned descendants stack level 0.
  7. the child stacking contexts positive stack levels (least positive first).

look, child stacking contexts negative stack levels, such div::after painted before the positioned descendants stack level 0, such div itself. explains behavior noticed.


Comments