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

Viewed 136

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>

3 Answers

It does follow the stack rules but it's position is not set yet ,you have to set the position to top: 0px;

You need to give .fx position attributes:

Usually a combination of either top or bottom plus either left or right.


Working Example:

.fx {
  position: fixed;
  top: 0;
  left: 0;
  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>

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>

Related