Tony Montana Tony Montana - 16 days ago 6
CSS Question

CSS - Z-index is not working with positions relative and absolute


I've made dropdown menu using pure css3, but one property(z-index) is not working as I expected and that is a very big problem, because the dropdown list is dropping ABOVE the menu. Ideally it must be dropped UNDER the menu. I've tried to do something with that problem all day but unfortunately can't figure it out, so now asking for help...
I've made a different background-colors for problem items for good seeing what i'm trying to reach. The main aim is that sub-menu with red background must be under the blue background.


P.S. I've already tried to make this menu with jQuery slideDown/slideUp properties but they don't look like ideal slide effect(as in my example). They look more like stretching, and that's not what I want..

EXAMPLE ON JSFIDDLE



ul {
list-style-type: none;
}
.menu_wrapper {
position: relative;
z-index: 999;
/* IS NOT WORKING... O_o...*/
height: 70px;
width: 600px;
background-color: blue;
}
.menu li {
display: inline;
float: left;
display: table;
height: inherit;
margin: 3px;
margin-top: 10px;
}
.menu li a {
display: table-cell;
font-family: Verdana;
font-size: 16px;
color: gold;
text-align: center;
text-decoration: none;
padding-left: 10px;
padding-right: 10px;
vertical-align: middle;
background: #05487F;
transition: .2s ease-in-out;
}
.sub-menu {
position: absolute;
z-index: 1;
/* IS NOT WORKING... O_o...*/
margin-top: -200px;
margin-left: -132px;
padding: 15px;
padding-top: 20px;
background-color: red;
transition: all 1s ease-in-out;
}
.sub-menu li {
float: none;
}
.sub-menu li a {
padding: 5px 15px;
}
.menu li a:hover + .sub-menu {
margin-top: 40px;
}
.sub-menu:hover {
margin-top: 40px;
}

<nav class="menu_wrapper">
<ul class="menu">
<li><a href="about/index.html">About</a>
</li>
<li><a href="news/index.html">News</a>
</li>
<li>
<a href="">PROBLEM HERE<br>(HOVER THIS)</a>
<ul class="sub-menu">
<li><a href="">link 1</a>
</li>
<li><a href="">link 2</a>
</li>
<li><a href="">link 3</a>
</li>
</ul>
</li>
<li><a href="">Something</a>
</li>
<li><a href="">Contacts</a>
</li>
</ul>
</nav>




Answer

The problem is that you're establishing a stacking context on .menu_wrapper when you set z-index: 999. When a stacking context is established, you cannot position a descendant element behind an ancestor.

Remove z-index: 999 from .menu_wrapper:

.menu_wrapper {
  position: relative;
  /* z-index: 999; << remove */
  height: 70px;
  width: 600px;
  background-color: blue;
}

Then change the z-index on .sub-menu from 1 to a negative number such as -1:

Updated Example

.sub-menu {
  position: absolute;
  z-index: -1;
  margin-top: -200px;
  margin-left: -132px;
  padding: 15px;
  padding-top: 20px;
  background-color: red;
  transition: all 1s ease-in-out;
}
Comments