Search code examples
htmlcssdomcss-positionz-index

Why position: fixed does not follow the stacking context rules?


Playing with the z-index of rel and rel1 will change the stacking position, but the fx will never be on top of them even with a higher z-index, unless is moved on top of the rels on DOM. Why is this happening ?

.fx {
  position: fixed;
  height: 30px;
  width: 30px;
  background-color: pink;
  margin-top: 60px;
  margin-left: 30px;
  z-index: 10000;
}

.rel {
  z-index: 7;
  position: relative;
  height: 500px;
  width: 200px;
  background-color: red;
  margin-top: 30px;
}

.rel1 {
  z-index: 6;
  position: relative;
  height: 500px;
  width: 100px;
  background-color: black;
  margin-top: -300px;
}
<div class="rel">
</div>

<div class="rel1">
</div>

<div class="fx">
</div>


Solution

  • As mdn says about position: fixed:

    Its final position is determined by the values of top, right, bottom, and left.

    So your code would look like this:

    .fx {
      position: fixed;
      height: 30px;
      width: 30px;
      background-color: pink;
      margin-top: 60px;
      margin-left: 30px;
      z-index: 10000;
      top: 20px;
      left: 10px;
    }
    
    .rel {
      z-index: 7;
      position: relative;
      height: 500px;
      width: 200px;
      background-color: red;
      margin-top: 30px;
    }
    
    .rel1 {
      z-index: 6;
      position: relative;
      height: 500px;
      width: 100px;
      background-color: black;
      margin-top: -300px;
    }
    <div class="rel">
      </div>
    
      <div class="rel1">
      </div>
    
      <div class="fx">
      </div>