1

Suppose I have the following HTML Code

HTML

<div class="a">
  <div class="b">
   <div class="c"></div>
  </div>
</div>

CSS

.a, .b, .c {
  width: 100px;
  height: 100px;
  position: relative;
}

.a {
  background: red;
   z-index: 999;
}

.b {
  background: green;
   margin: 40px;
   z-index: 500;
}

.c {
  background: gray;
  margin: 40px;
  z-index: 100;
}

Now, i want it to be exactly opposite i.e, red on top of all. I tried using z-index with position set to relative but it doesn't work. Here's the jsfiddle demo

Ashish Rawat
  • 3,363
  • 5
  • 29
  • 35
  • Just to be sure, you want to have red div on top, green in middle and gray at the bottom using either javascript or jQuery? – RooKie- Oct 18 '13 at 16:55
  • The stacking context resets whenever you nest elements — aka the `z-index` values are only relevant when comparing siblings, not when comparing parent-child nesting. The parent will ALWAYS be behind the children, regardless of the z-index. – Terry Oct 18 '13 at 16:57
  • http://stackoverflow.com/questions/1806421/css-parent-element-to-appear-above-child – Tom Bowers Oct 18 '13 at 17:00

1 Answers1

3

You can't. The parent will always be behind the children, as z-index values are stacked.

The order in which the rendering tree is painted onto the canvas is described in terms of stacking contexts. Stacking contexts can contain further stacking contexts. A stacking context is atomic from the point of view of its parent stacking context; boxes in other stacking contexts may not come between any of its boxes. - W3 http://www.w3.org/TR/CSS2/visuren.html#z-index

By setting a z-index on .a, you are also setting the same z-index on all the children. For instance, by setting z-index:999 on .a -- .b, and .c now also have the same indexes, rending it useless. To achieve this, the elements cannot be a parent nor a child of another, they would have to be siblings for this to work.

Here is what it would look like if they are siblings - it works!

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304