Search code examples
htmlcsslayoutoverlaypositioning

How can I have a transparent <div> in front of every other element


So I was trying to create a div that would be alpha:0 on top of the page and have an animation to "darken" the rest of the website with a popup on top.

While this in theory sounded easy to do, I kept fiddling with positions absolute/relative/fixed to try and achieve this, but no success.

What I have right now is an element inside an element, my problem I can't bring it to the back of the webpage, even with z-index.

What would be your simplest solution to have a transparent div over any other element? (except the pop-up)

My code at the moment:

<body>
    <div position="fixed" style="background-color: rgba(0, 0, 0, 1); border: 1px solid green; height: 100vh; width: 100vw; top:0; z-index: 10">
        <div position="absolute" class="header" id="header" style="border:1px solid green; background-color: white; height:30px; width:250px; top:0; z-index: -1"></div>
    </div>
</body>

Solution

  • Write the overlay below the other div and put them both in position: absolute;. If you want the anything above the overlay use the same logic. Add another div below the overlay. You can also add on in the overlay.

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    html,
    body {
      height: 100%;
      min-height: 100%;
    }
    <body>
    
      <!-- your content -->
      <div class="header" id="header" style="position: absolute;border:1px solid green; background-color: white; height:30px; width:250px;">
      </div>
    
      <!-- the overlay -->
      <div style="position: absolute; background-color: rgba(0, 0, 0, 0.8); border: 1px solid green; height: 100%; width: 100%;">
      </div>
    
    </body>

    Also note that I move the position: absolute; instide the style. By the way, you should move it again to a css file :)