CSS我希望div放在一切之上


Answers:


120

为了使z-index正常工作,您需要为元素指定a position:absoluteposition:relative属性。完成此操作后,您的链接将正常运行,尽管之后可能需要稍微调整一下CSS。


我想使用固定方案,因此我将位置保持不变,但仍将z-index设置为1000并获得了预期的结果,当我滚动时它覆盖了页面的div较低,即使这样也可以解释为什么会发生这种情况我使用的是静态位置?
Boo89100 '16

37

对于 z-index:1000产生效果,您需要一个非静态的定位方案。

添加position:relative;到规则中,选择要放在顶部的元素


24

是的,为了使z-index正常工作,您需要为该元素提供position:absolute或position:relative属性。

但是...注意父母!

您必须上移元素的节点,以检查在共同父级的级别上,第一个后代是否具有已定义的z-index。

如果在底部有一个较低的确定z索引,则所有其他子孙都永远不会在前台。

在此代码段示例中,div1-2-1的z索引为1000,但仍低于div1-1-1的z索引为3。

这是因为div1-1的z索引大于div1-2。

在此处输入图片说明

.div {
  
}

#div1 {
  z-index: 1;
  position: absolute;
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

#div1-1 {
  z-index: 2;
  position: absolute;
  left: 230px;
  width: 200px;
  height: 200px;
  top: 31px;
  background-color: indianred;
}

#div1-1-1 {
  z-index: 3;
  position: absolute;
  top: 50px;
  width: 100px;
  height: 100px;
  background-color: burlywood;
}

#div1-2 {
  z-index: 1;
  position: absolute;
  width: 200px;
  height: 200px;
  left: 80px;
  top: 5px;
  background-color: red;
}

#div1-2-1 {
  z-index: 1000;
  position: absolute;
  left: 70px;
  width: 120px;
  height: 100px;
  top: 10px;
  color: red;
  background-color: lightyellow;
}

.blink {
  animation: blinker 1s linear infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}

.rotate {
  writing-mode: vertical-rl;
  padding-left: 50px;
  font-weight: bold;
  font-size: 20px;
}
<div class="div" id="div1">div1</br>z-index: 1
  <div class="div" id="div1-1">div1-1</br>z-index: 2
    <div class="div" id="div1-1-1">div1-1-1</br>z-index: 3</div>
  </div>
  
  <div class="div" id="div1-2">div1-2</br>z-index: 1</br><span class='rotate blink'><=</span>
    <div class="div" id="div1-2-1"><span class='blink'>z-index: 1000!!</span></br>div1-2-1</br><span class='blink'> because =></br>(same</br>   parent)</span></div>
  </div>
</div>


你是救星!
本杰明·卡洛格

16

您需要添加position:relative;到菜单。Z-index仅在您具有非静态定位方案时才有效。


9

z-index属性使您可以控制自己。您设置的数字越大,获得的元素就越高。

position属性应该是relative因为的位置html-element在所有维度上都应相对于其他控件处于相对位置。

element.style {
   position:relative;
   z-index:1000; //change your number as per elements lies on your page.
}

4

我会以为您会弹出来自WW3学校的代码,对吗?检查它的CSS。.modal一个,那里已经有字了z-index。只需从1更改为100。

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.