2

I am trying to get a child element behind its parent element.

Both have position: absolute and z-index (parent z-index is 3, and child is -1), but the child still appears in front of the parent.

I have recreated the problem here (click on the missing image to show the submenu that should appear BEHIND the nav): https://jsfiddle.net/fr2gaq6d/

nav {
    position:absolute;
    z-index:3;
}

#nav_areas {
    display:none;
    position:absolute;
    top:0.5em;
    left:0;
    right:0;
    background-color:#fff;
    z-index: -1;
    color:#212121;
}

What am I doing wrong?

Gaurav Aggarwal
  • 9,809
  • 6
  • 36
  • 74
abd
  • 379
  • 3
  • 14

1 Answers1

2

When you use z-index:3 on the nav, it establishes a stacking context.

Elements inside that stacking context can only be z-aligned inside it, but not placed below it.

If you remove that z-index:3, it won't establish a stacking context, and then the z-index:-1 of the child will place it behind the nav.

document.getElementById('menu_toggle').addEventListener("click", function() {
  menuToggle();
});
function menuToggle() {
  if (document.getElementById('nav_areas').style.display == 'none' || document.getElementById('nav_areas').style.display == '') {
    changeNavAreasVisibility(true);
  } else {
    changeNavAreasVisibility(false);
  }
}
function changeNavAreasVisibility(isVisible) {
  if (isVisible) {
    document.getElementById('nav_areas').style.display = 'initial';
  } else {
    document.getElementById('nav_areas').style.display = 'none';
  }
}
nav {
  background-color: #9C27B0;
  text-transform: uppercase;
  text-align: center;
  left: 0;
  right: 0;
  display: flex;
  color: #fff;
}
#menu_toggle {
  height: 1em;
  cursor: pointer;
  order: 3;
  display: inline;
}
nav {
  position: absolute;
  /*z-index:3;*/
}
#nav_areas {
  display: none;
  position: absolute;
  top: 0.5em;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: -1;
  color: #212121;
}
<nav>
  <div>
    ASDF ASDF ASDF ASDF ASDF
  </div>
  <ul id="nav_areas">
    <li>ITEM 1</li>
    <li>ITEM 2</li>
    <li>ITEM 3</li>
    <li>ITEM 4</li>
  </ul>
  <ul id="nav_etc">
    <li id="nav_etc_search">
      <input type="search" placeholder="Search...">
    </li>
  </ul>
  <img id="menu_toggle" src="menu.svg" alt="menu">
</nav>
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • That worked, but now i have another problem, the submenu is appearing below the content (updated code: https://jsfiddle.net/fr2gaq6d/3/). Is there a way to make it appear below the nav, but above the content? Should i put a z-index-2 on the content? – abd Mar 31 '16 at 02:14
  • @abd You can wrap the nav inside an element with `position: relative` and non-`auto` `z-index`. That will create a stacking context. – Oriol Mar 31 '16 at 08:27