How do you get the position: absolute; item above position: relative; one

You can see the problem in this script .

I have an absolutely positioned element with z-index 2 and a relatively positioned element with z-index 1. A relatively positioned element contains an absolutely positioned element. I thought the z-index: 2 element would render above the z: 1 index, but it doesn't. Is there a way to fix this so that the z-index: 2 elements are above the entire z-index: 1 element?

div {
  background: green;
  position: relative;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}
      

<div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div>
      

Run codeHide result


+3


source to share


3 answers


When you add z-index

to a child that is in a positioned parent that also has z-index

, the parent z-index

starts the new stacking order, and the child z-index

belongs to the parent z-index

. So in this case it z-index: 2

only compares to other elements inside the parent with z-index: 1

. To get around this, you can simply apply z-index

to span

or not give the last div

az-index

You can read more about this here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context



body {
  font-family: arial;
}

* {
  padding: 10px;
}

div {
  background: green;
  position: relative;
  width: 100%;
  
}

div:first-child {
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
  display: inline-block;
}
      

<div>
  Row 1
  <span>
  I thought this would show above 'Row 2'
</span>
</div>
<div>
  Row 2
</div>
      

Run codeHide result


+5


source


The problem was that the div with absolute position was not relative to the second line. I added a wrapper around two divs and added position: relative;

to it.



.wrapper div {
  background: green;
  width: 100%;
  z-index: 1;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}

.wrapper {
  position: relative;
}
      

<div class="wrapper">
  <div>
    Row 1
    <span>I thought this would show above 'Row 2'</span>
  </div>
  <div>
    Row 2
  </div>
</div>
      

Run codeHide result


0


source


Just remove z-index:1

.

div {
  background: green;
  position: relative;
  width: 100%;
}

span {
  top: 0;
  right: 0;
  z-index: 2;
  position: absolute;
  border: solid 1px red;
  height: 70px;
  background: white;
}
      

<div>
  Row 1
  <span>I thought this would show above 'Row 2'</span>
</div>
<div>
  Row 2
</div>
      

Run codeHide result


0


source







All Articles