尽管z-index较低,但我的绝对定位div正在覆盖我的另一个div

时间:2018-04-18 15:16:32

标签: html css

这很奇怪,即使复制粘贴代码,我也无法在jsfiddle中复制错误。

基本上我有这样的话:

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

使用这个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;
}

这应该在屏幕顶部显示一个红色框,就像在这个小提琴中一样:https://jsfiddle.net/Lmj6d625/

然而,在我的实际页面中(在同一浏览器上),蓝色涵盖了一切。我甚至可以在下面添加新的div文本,它们完全隐藏。

截图:

Where is my div?!

任何人都有任何建议如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

1。)DIV标签不能自动关闭

2。)您需要body标记的高度,否则它将具有0高度,这也将适用于container.absolute-background,使其不可见。

3。)您需要position: absoluteposition: relative才能使红色DIV的z-index生效(fixed也会有效,但之后就不会滚动与页面的其余部分)

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>

答案 1 :(得分:0)

z-index属性仅适用于位置值不是静态的元素(例如position:absolute;,position:relative;,或position:fixed)。

还有位置:粘性;在Firefox中支持,在Safari中加上前缀,在自定义标记下的旧版Chrome中工作了一段时间,Microsoft正在考虑将其添加到Edge浏览器中。 感谢Evert的回答