Search code examples
cssz-indexfixedabsolute

Z-index in front of an element in a fixed position


I do not find a solution to my problem so I turn to you :).

Here is the context: I have two brothers elements, one is absolute position and the other is in a fixed position. Basic the fixed element is always at the top. Consider in the code below:

* {
  box-sizing: border-box;
}
html, body{
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}
#element1 {
  background: red;
  height: 100%;
  width: 100%;
  position: absolute;
}
#element2 {
  background: green;
  margin: 0 auto;
  height: 200px;
  position: absolute;
  width: 600px;
}
#element3 {
  background: blue;
  height: 200px;
  position: fixed;
  bottom: 0;
  width: 100%;
}

#element1,
#element3 {
  z-index: 1;
}	
#element2 {
  z-index: 10;
}
<div id="element1">
  <div>
     <div id="element2"></div>
  </div>
</div>
<div id="element3">

</div>

http://jsfiddle.net/P7c9q/1162/

That the green color area is a modal. My objective is to make the element green over the element in a fixed position.

How can I unlock myself knowing that element 1 and element 2 must remain in absolute position?

Thank you in advance, cordially.


Solution

  • element3 will always be over element1 and all its children even if a child of element1 has higher z-index because its finally related to its parent element1 which has lower z-index than element3

    There are two solutions to this case:

    1. put element2 and element3 as children for element1

    * {
      box-sizing: border-box;
    }
    html, body{
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }
    #element1 {
      background: red;
      height: 100%;
      width: 100%;
      position: absolute;
    }
    #element2 {
      background: green;
      margin: 0 auto;
      height: 200px;
      position: absolute;
      width: 600px;
    }
    #element3 {
      background: blue;
      height: 200px;
      position: fixed;
      bottom: 0;
      width: 100%;
    }
    
    #element1,
    #element3 {
      z-index: 1;
    }	
    #element2 {
      z-index: 10;
    }
    <div id="element1">
      <div>
         <div id="element2"></div>
      </div>
      <div id="element3">
    
      </div>
    </div>

    1. make element2 outside element1 in the same level with element3

    * {
      box-sizing: border-box;
    }
    html, body{
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }
    #element1 {
      background: red;
      height: 100%;
      width: 100%;
      position: absolute;
    }
    #element2 {
      background: green;
      top:25%;
      left:15%;
      margin: 0 auto;
      height: 200px;
      position: fixed;
      width: 600px;
    }
    #element3 {
      background: blue;
      height: 200px;
      position: fixed;
      bottom: 0;
      width: 100%;
    }
    <div id="element1"></div>
    <div id="element2"></div>
    <div id="element3"></div>