Ashish Rawat
Ashish Rawat

Reputation: 3513

How to reverse the order of nested child elements

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

Upvotes: 1

Views: 1004

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240878

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!

Upvotes: 3

Related Questions