z-index 不适用于我的下拉菜单

z-index isn't working for my dropdown menu

我有一个导航栏,下拉菜单是绝对定位的,但出于某种原因,它们仍然出现在所有其他定位项的后面,无论 z-index 是什么。这使得菜单既难看又难以在带有定位项的页面上使用。 Here is a codepen 显示了我的导航栏及其存在的问题。有人知道怎么回事吗?

这是我的 css 的一小部分,因为我认为您不需要我的问题中的全部 150 行代码:

header nav ul li ul {
    background-color: #00242b;
    transition: opacity 400ms ease-in;
    opacity: 0;
    position: absolute;
    height: 0px;
    z-index: 1000000000; /* why wont this work? */
    overflow: auto;
    transform: translate(0px, 0px);
    overflow: auto;
}
#absolute { /* this is on top despite the lower z-index */
    position: absolute;
    width: 80px;
    height: 40px;
    background-color: red;
    z-index: 0;
    left: 20px;
    top: 80px;
}

首先,尽量不要使用这么高的z-index。从 1、10、50、100 左右开始。这样当你有一个非常高的元素时,你想要覆盖所有获得最高数字的元素

要解决这个问题:从其他任何地方删除 z-index 并从首先要高的元素开始。

在这种情况下

header nav {
   z-index: 1;
}

默认为z-index: auto

您的 nav 元素有 position: sticky; 但没有 z-index。这意味着位于其中的任何内容都将基于 nav 父级定位自身。如果您向该 nav 元素添加一个高于页面上任何其他元素的 z-index 数字,您的导航将按预期运行。

使用你的例子,红框有z-index: 1;。如果您将 z-index: 2; 添加到 nav 元素,那么您的整个导航将位于其上方。

一旦此修复到位,就不需要 nav 的任何子元素进行 z 索引,因为父元素已经位于页面上所有其他元素之上。