Search code examples
cssz-index

z-index isn't working for my dropdown menu


I have a navigation bar, and the dropdowns are absolutely positioned, but for some reason, they still appear behind all other positioned items, no matter what the z-index. This makes the menu both ugly and difficult to use on pages with positioned items. Here is a codepen that shows my navigation bar and the problem it's having. Does anyone know what's wrong?

Here's a small spinet of my css since I don't think you want the full 150 lines of code in my question:

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;
}


Solution

  • Your nav element has position: sticky; but doesn't have any z-index. This means that anything positioned inside it is going to be positioning itself based off of that nav parent. If you add a z-index number higher than any other element on the page to that nav element, your nav will behave as you expect.

    To use your example, the red box has z-index: 1;. If you add z-index: 2; to the nav element then your entire navigation will sit above it.

    There is no need to have any of the children of nav z-indexed once this fix is in place as the parent element will positioned above everything else on the page already.