z-index不使用位置绝对值

时间:2013-01-23 15:47:54

标签: html css

我打开控制台(chrome \ firefox)并运行以下行:

$("body").append("<div id=\"popupFrame\" style=\"width:100%;height:100%;background-color:black;opacity:0.5;position:absolute;top:0;left:0;z-index:1;\" />");
$("body").append("<div id=\"popupContent\" style=\"width:200px;height:200px;z-index:1000;background-color:white;\" >dasdasdsadasdasdasdasdasd</div>");

#popupContent应该是最重要的,但它受#popupFrame不透明度的影响。

内容未包含在#popupFrame中,这使得这非常奇怪。

目标是创建类似警告框的火狐

我会感激任何帮助。

提前致谢。

5 个答案:

答案 0 :(得分:184)

第二个div是position: static(默认值),因此z-index不适用于它。

您需要定位(将位置属性设置为除static以外的任何其他内容,在这种情况下您可能需要relative)您希望提供z-index的任何内容。

答案 1 :(得分:34)

不透明度会改变z-index的上下文,静态定位也是如此。要么将不透明度添加到没有它的元素,要么将其从元素中删除。您还必须使两个元素静态定位或指定相对或绝对位置。以下是有关上下文的一些背景知识:http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

答案 2 :(得分:23)

z-index仅适用于已明确定位的元素。将position:relative添加到#popupContent,您应该很高兴。

答案 3 :(得分:20)

老问题,但这个答案可能对某人有帮助。

如果您尝试在容器边界之外显示容器的内容,请确保它没有using System.Collection.Generic.List ,否则其外的任何内容都将被切断。

答案 4 :(得分:0)

在使用position: absolute;时,我经常遇到这个问题,在子元素中使用position: relative时,我遇到了这个问题。无需将position: absolute更改为relative,只需在子元素中添加以下两个示例即可:

let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>

这是使用相对位置固定的方法:

let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
  
  // Just add position relative;
  position: relative;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>

Sandbox here

相关问题