How to get a parent element to appear above child

Jourkey picture Jourkey · Nov 27, 2009 · Viewed 101.4k times · Source

I have two nested CSS elements. I need to get the parent to be on top, that is, above in z-axis, of the child element. Just setting z-index is not sufficient.

I can't set a negative z-index on the child, that'll set it to below the page container on my actual page. Is this the only method?

http://jsbin.com/ovafo/edit

.parent {
  position:  relative;
  width: 750px;
  height: 7150px;
  background: red;
  border: solid 1px #000;
  z-index: 1;
}
.child {
  position: absolute;
  background-color: blue;
  z-index: 0;
  color: white;
  top: 0;
}
.wrapper
{
  position: relative;
  background: green;
  z-index: 10;
}
<div class="wrapper">
  <div class="parent">
    parent parent
    <div class="child">
      child child child
    </div>
  </div>
</div>

Answer

Alan Haggai Alavi picture Alan Haggai Alavi · Nov 27, 2009

Set a negative z-index for the child, and remove the one set on the parent.

.parent {
    position: relative;
    width: 350px;
    height: 150px;
    background: red;
    border: solid 1px #000;
}
.parent2 {
    position: relative;
    width: 350px;
    height: 40px;
    background: red;
    border: solid 1px #000;
}
.child {
    position: relative;
    background-color: blue;
    height: 200px;
}
.wrapper {
    position: relative;
    background: green;
    height: 350px;
}
<div class="wrapper">
    <div class="parent">parent 1 parent 1
        <div class="child">child child child</div>
    </div>
    <div class="parent2">parent 2 parent 2
    </div>
</div>

https://jsfiddle.net/uov5h84f/