CSS转换和z-index

boo*_*oop 9 css css3 css-transitions css-animations

我有一个带下拉菜单的固定顶部导航栏.我想在悬停时滑动下拉菜单.我希望菜单在滑动时位于导航栏后面.所以我只是尝试设置z-index两个元素,但遗憾的是这对我不起作用.

这是一个简化的例子(codepen)

HTML

<div class="fixed-top">
  <span class="trigger">hover me</span>
  <div class="menu"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.fixed-top {
  background: #3b5999;
  height: 50px;
  width: 100%;
  padding: 0;
  top: 0;
  position: fixed;
  z-index: 2;
}

.trigger {
  z-index: 2;
  font-size: 33px;
  color: white;
  margin-left: 50%;
}

.trigger:hover + .menu {
  margin-top: 0;
}

.menu {
  z-index: 1;
  height: 300px;
  background-color: #1c7754;
  width: 400px;
  margin: auto;
  margin-top: -400px;
  transition: all 0.75s ease-out;
}
Run Code Online (Sandbox Code Playgroud)

如果我不清楚我想在这里做一个简单的mspaint草图;)

mspaint技能证实

bow*_*art 6

当开始使用CSS中的堆叠上下文时,这是一个非常常见的错误.基本上,您只需要记住,子项不能存在于父项的不同堆栈上下文中.

因此,如果我有一个非静态元素(意思是一个元素position: anything-but-static [fixed, relative, absolute]),并且该元素没有非静态父元素,那么无论它在DOM中的哪个位置,它都将处于堆栈上下文级别1.现在,如果该元素具有非静态子元素,则该子元素将处于堆叠上下文级别2. 它不能与其父元素位于同一级别(级别1). z-index只能影响同一堆叠上下文级别的元素,它与不同堆叠上下文级别的元素无关.

解决方案是重构HTML,或者只使用:before:after伪元素,因此:

.fixed-top {
    height: 50px;
    width: 100%;
    padding: 0;
    top: 0;
    position: fixed; /* The parent: stacking context level 1 */
}
.fixed-top:before {
    background: #3b5999;
    content:'';
    position: absolute; /* stacking context level 2 */
    top: 0; right: 0; bottom: 0; left: 0;
    z-index: 1;
}
.trigger {
    color: white;
    font-size: 33px;
    margin-left: 50%;
    position: relative; /* also stacking context level 2 */
    z-index: 2;
}
.trigger:hover + .menu {
    margin-top: 0;
}
.menu { /* bottom layer -- no stacking context necessary */
    z-index: 0;
    height: 300px;
    background-color: #1c7754;
    width: 400px;
    margin: auto;
    margin-top: -400px;
    transition: all 0.75s ease-out;
}
Run Code Online (Sandbox Code Playgroud)

请注意表示堆叠上下文级别的注释.

这里有一个JSFiddle的例子.


kol*_*nar 4

尝试运行代码片段。

.fixed-top {
  background: #3b5999;
  height: 50px;
  width: 100%;
  padding: 0;
  top: 0;
  position: fixed;
  z-index: 2;
}

.trigger {
  font-size: 33px;
  color: white;
  margin-left: 50%;
  width: 100%;
  height: 50px;
  top: 0;
  position: fixed;  
  z-index: 3;  
}

.trigger:hover + .menu,
.menu:hover{
  margin-top: 0;
}

.menu {
  z-index: 1;
  height: 300px;
  background-color: #1c7754;
  width: 400px;
  margin: auto;
  margin-top: -400px;
  transition: all 0.75s ease-out;
}
Run Code Online (Sandbox Code Playgroud)
<div class="fixed-top"></div>
<span class="trigger">hover me</span>
<div class="menu"></div>
Run Code Online (Sandbox Code Playgroud)