Search code examples
htmlcssz-index

Sub-menu links still clickable when main menu drop-downs are closed


I'm trying to create a setup where I have a navbar, a collapsible menu within the navbar, and website content.

Sorry for the bad example but kind of like this: https://jsfiddle.net/2nqchLpf/

As you can see if you hover over the sub-menu links when the dropdown is not expanded, you can still click on them.

How can I get the links to display behind the content while having the navbar display over everything?

I have applied z-index like this:

.navbar {
    position: fixed;
    z-index: 1000;
}

.big-dropdown {
    position: absolute;
    z-index: -1;
}

#content {
    position: relative;
    z-index: 999;
}

Solution

  • It's tricky with z-index, considering stacking order and other z-index characteristics. Here's a complete run-down: Basics of the CSS z-index property

    But for a simple and easy solution, since you're already using position: absolute, just move the sub-links off the screen.

    So instead of this:

    .big-dropdown {
      opacity: 0;
      height: 200px;
      background-color: #fff;
      position: absolute;
      left: 0;
      top: 0;
      margin-top: 4em;
      width: 100%;
    }
    
    .show {
      opacity: 1!important;
    }
    

    Try something like this:

    .big-dropdown {
      opacity: 0;
      height: 200px;
      background-color: #fff;
      position: absolute;
      left: -9999px; /* adjustment */
      top: 0;
      margin-top: 4em;
      width: 100%;
    }
    
    .show {
      opacity: 1!important;
      left: 0; /* new */
    }
    

    revised fiddle