简体   繁体   中英

My absolute positioned div is covering my other div despite lower z-index

This is so strange that I can't even replicate the error in jsfiddle despite copy-pasting the code.

Basically I have it like this:

<div class="container">
    <div class="absolute-background" />
    <div class="where-is-this" />
</div>

With this CSS:

.container {
  background: transparent;
  position: relative;
  overflow: hidden;
  height: 100%;
  width: 100%;
}

.absolute-background {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  background: blue;
  z-index: 0;
}

.where-is-this {
  height: 100px;
  width: 100%;
  z-index: 1000000;
  background: red;
}

This should display a red box at the top of the screen, as it does in this fiddle: https://jsfiddle.net/Lmj6d625/

However, in my actual page (on the same browser) the blue covers EVERYTHING. I can even add new div s below with text and they are completely hidden.

Screenshot:

Where is my div?!

Anyone have any suggestions how to troubleshoot this?

1.) DIV Tags can't be self closing

2.) You need a height for the body tag, otherwise it will have 0 height, and that will also apply to container and .absolute-background , making them invisible.

3.) You need position: absolute or position: relative for the z-index of the red DIV to become effective ( fixed would also work, but then it wouldn't scroll with the rest of the page)

 html, body { height: 100%; margin: 0; } .container { background: transparent; position: relative; overflow: hidden; height: 100%; width: 100%; } .absolute-background { position: absolute; height: 100%; width: 100%; left: 0; top: 0; background: blue; z-index: 0; } .where-is-this { position: absolute; height: 100px; width: 100%; z-index: 1000000; background: red; } 
 <div class="container"> <div class="absolute-background"></div> <div class="where-is-this"></div> </div> 

The z-index property only works on elements with a position value other than static (eg position: absolute;, position: relative;, or position: fixed).

There is also position: sticky; that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser. Thanks to Evert for this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM