0

I am trying to figure out why a child element does not appear behind its parent element when given a lower z-index value than the parent. It only appears to work when you do not touch the parent's default z-index value.

Here's a basic example.

HTML:

<div class="a">
    A DIV
    <div class="b">
        B DIV
    </div>
</div>

CSS:

.a {
    position: relative;
    background: #eaeaea;
    height: 200px;
    width: 200px;
    z-index: 20;
}
.b {
    position: relative;
    z-index: -20;
    background: #d6d6d6;
    height: 100px;
    width: 100px;
}

Link to example: http://jsfiddle.net/V4786/2/

Any thoughts would be appreciated.

user12893298320392
  • 385
  • 1
  • 4
  • 13
  • Maybe because if it is inside the parent it will be on the same z-index as the parent. It needs to not be in the parent to be on its own z-index. – John Conde Nov 12 '13 at 02:57
  • 1
    `z-index` values are stacked... see [How to reverse the order of nested child elements](http://stackoverflow.com/questions/19454901/how-to-reverse-the-order-of-nested-child-elements) – Josh Crozier Nov 12 '13 at 03:02
  • 1
    what you are looking for is `stacking context` https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context – Lucky Soni Nov 12 '13 at 03:03

2 Answers2

1

Because Z-Index levels are relative to their parents. This is the same as saying "Why doesn't the element show behind the browser window if I set a negative Z-Index?" Generally if you're going to do something funky with levels, you might consider having two sibling elements with absolute or relative positioning. Although that approach is sometimes considered "hacky."

Scotty C.
  • 744
  • 4
  • 16
1

It only appears to work when you do not touch the parent's default z-index value.

This is because setting z-index to something other than its default auto on a positioned element causes it to establish a new stacking context, and an element cannot be positioned behind the element that created the stacking context that it's in. (An element cannot be positioned behind the root stacking context, for example, as Scotty C. states.)

When you leave the z-index of the parent element untouched, the parent and the child both participate in the same stacking context, which is the one established by the root element, or the root stacking context. This is why you can position the child behind the parent in such a case.

All the details can be found in the spec, but that's the gist of it given your question.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356