Search code examples
htmlcsspositionz-index

Why doesn't z-index work although with specified "position"?


I have read that in order for z-index to take effect, the CSS elements involved need to have "position" attributes. So I have a menu that I would like to appear over an IMG when someone clicks on the menu icon. I have these styles for the menu and the image in the content area ...

.menu-btn div {
    position: absolute;
    left: 100%;
    top: 0%;
    padding-right: 8px;
    margin-top: -0.50em;
    line-height: 1.2;
    font-weight: 200;
    vertical-align: middle;
    z-index: 99;
} 

#personImgDiv {
    position: relative;
    z-index: 100;
    display: table-cell;
    width: 80%;
}

However, when I click on the menu icon, the menu is still appearing behind the image -- https://jsfiddle.net/bdcmka1r/2/ . What else am I missing? How do I get the menu to always appear in front?


Solution

  • This is because you're using the wrong selector. .menu-btn is the button class, and it will only affect this button, also there is no way a button can be treated as a container element such as div, nav, header ..etc. Your correct selector will be nav since your menu contained within nav tags. So, you need to add the position and z-index properties to nav selector instead.

    nav {
      display: none;
      width: 100vw;
      padding: 0rem;
      background-color: red;
      position: absolute;
      z-index: 9999;
      right: 0%;
      top: 100%;
      text-align: left; 
    }