NewbornCodeMonkey
NewbornCodeMonkey

Reputation: 198

Position Fixed Child Restricted By Position Relative Parent Container's Z-index

Position Fixed elements always position themselves relative to the window.

However, if the position fixed element is inside of a position relative container, the position fixed child will obey the z-index of the position relative container. This means if any siblings of the container are also relative and have a higher z-index, they will cover the position fixed child.

Example: https://jsfiddle.net/r4n6Lzhx/2/

<style>

.container1 {
  position: relative;
  z-index: 2;
  height: 200px;
  width: 100%;
  background-color: yellow;
  box-shadow: 5px 5px 3px #888888;
}

.container2 {
  position: relative;
  background-color: green;
  z-index: 1;
  height: 200px;
}

.overlay {
  position: fixed;
  top: 50px;
  left: 50px;
  right: 50px;
  bottom: 50px;
  background: black;
  opacity: .8;
  z-index: 3;
}

</style>

<div class="container1"></div>
<div class="container2">
   <div class="overlay"></div>
</div>

Is there a way to make the position fixed child "escape" the parent's z-index by changing only the child's CSS and not the parent's?

The desired end result is container 1 covering container 2, but the overlay (that is a child of container 2) covering container 1, and I cannot change the CSS of container1 or container 2.

Upvotes: 0

Views: 2555

Answers (1)

Setting container1 absolute and container2 relative will overlap them

z-index of container1 needs to be greater than the z-index of container2 and same for overlay and container1. Then if you doesn't set z-index of container2 it will be 0 and for container1 can be 1 and overlay 2.

I edited the width of container1 to see the container2 behind, you can set it back to 100%.

.container1 {
  position: absolute;
  z-index: 1;
  height: 200px;
  width: 90%;
  background-color: yellow;
  box-shadow: 5px 5px 3px #888888;
}

.container2 {
  position: relative;
  background-color: green;
  height: 200px;
}

.overlay {
  position: fixed;
  top: 50px;
  left: 50px;
  right: 50px;
  bottom: 50px;
  background: black;
  opacity: .8;
  z-index: 2;
}
<div class="container1"></div>
<div class="container2">
 <div class="overlay"></div>
</div>

Upvotes: 1

Related Questions