Search code examples
htmlcsscss-positionz-index

How to place a standalone fixed-Div layered between(z-index) a fixed Parent and Absolute-Child division?


I have two fixed components:

  1. Parent with its absolute positioned Child
  2. Between

I have used z-index for all three elements but those aren't a must. I cannot remove the z-index:666 of the parent nor can I remove its position:fixed as it'll mess-up the site layout...

rest z-indices can be changed... the goal is to bring the Between element between Parent and Child elements...

Here's my Code:

* {
  color: white;
  width: 40vw;
  height: 30vh;
  text-align: right;
  padding: 1rem
}

#parent {
  position: fixed;
  top: 30vh;
  height: 50vh;
  background: red;
  left: 0;
  right: 0;
  width: auto;
  z-index: 666;
}

#child {
  position: absolute;
  top: 5vh;
  background: orange;
  left: 30vw;
  z-index: 888;
}

#between {
  position: fixed;
  top: 40vh;
  background: green;
  left: 10vw;
  z-index: 777;
}
<div id="parent">
  Parent
  <div id="child">
    Child
  </div>
</div>
<div id="between">
  Between
</div>


Solution

  • An idea of solution that works but will break the position:fixed. It uses 3D transformation tricks

    body * {
      color: white;
      width: 40vw;
      height: 30vh;
      text-align: right;
      padding: 1rem
    }
    
    #parent {
      position: fixed;
      top: 30vh;
      height: 50vh;
      background: red;
      left: 0;
      right: 0;
      width: auto;
      z-index: 666;
    }
    
    #child {
      position: absolute;
      top: 5vh;
      background: orange;
      left: 30vw;
      z-index: 888;
      transform:translateZ(2px); /* here */
    }
    
    #between {
      position: fixed;
      top: 40vh;
      background: green;
      left: 10vw;
      z-index: 777;
    }
    
    html {
      transform-style:preserve-3d; /* here */
    }
    <div id="parent">
      Parent
      <div id="child">
        Child
      </div>
    </div>
    <div id="between">
      Between
    </div>

    Related: Why can't an element with a z-index value cover its child?