我有一个带下拉菜单的固定顶部导航栏。我想在悬停时滑动下拉菜单。我希望菜单在滑动时位于导航栏后面。所以我只是尝试设置两个元素的z-index
,但遗憾的是这些元素对我不起作用。
这是一个简化的例子(codepen)
HTML
<div class="fixed-top">
<span class="trigger">hover me</span>
<div class="menu"></div>
</div>
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;
}
如果我不清楚我想在这里做一个简单的mspaint草图;)
答案 0 :(得分:6)
开始使用CSS中的堆叠上下文时,这是一个非常常见的错误。基本上,您只需要记住,孩子不能存在于父母的不同堆叠环境中。
因此,如果我有一个非静态元素(意思是一个带有position: anything-but-static [fixed, relative, absolute]
的元素),并且该元素没有非静态父元素,那么它将处于堆叠上下文级别1,无论它在哪里在DOM中。现在,如果该元素具有非静态子元素,则该子元素将处于堆叠上下文级别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;
}
请注意表示堆叠上下文级别的注释。
这里有一个JSFiddle例子。
答案 1 :(得分: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;
}
<div class="fixed-top"></div>
<span class="trigger">hover me</span>
<div class="menu"></div>
答案 2 :(得分:0)
我认为这就是你想要的。
css代码
.fixed-top {
background: #3b5999;
height: 50px;
width: 100%;
padding: 0;
top: 0;
position : fixed;
}
.trigger {
z-index: 500;
font-size: 33px;
color: white;
margin-left: 50%;
position : absolute;
}
.trigger:hover + .menu {
margin-top: 0;
}
.menu {
z-index: -9999;
position : relative;
height: 300px;
background-color: #1c7754;
width: 400px;
margin: auto;
margin-top: -400px;
transition: all 0.75s ease-out;
}
<div class="fixed-top">
<span class="trigger">hover me</span>
<div class="menu"></div>
</div>
这是您可以查看的参考资料
http://www.smashingmagazine.com/2009/09/the-z-index-css-property-a-comprehensive-look/