Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Z-index: How to make nested elements appear underneath their parent element

This fiddle should demonstrate the issue:

http://jsfiddle.net/5sqxQ/2/

I want the sub menu to appear underneath the parent menu. I was then was looking to extend this with JavaScript to slide the menu from underneath on hover of the parent li element.

Not fussed about the JavaScript but can't figure out how to style the elements to achieve the desired layering.

like image 368
RyanP13 Avatar asked Jun 27 '11 13:06

RyanP13


People also ask

Does Z index place the element behind its parent?

z-index is based on elements at the same level in the DOM, in other words, elements with the same parent. Since your class="dropdown" element is a child of the class="background" element it can never be below its parent.

How do I make my child's Z index higher than my parents?

This is impossible as a child's z-index is set to the same stacking index as its parent. You have already solved the problem by removing the z-index from the parent, keep it like this or make the element a sibling instead of a child.

Does Z Index work with position relative?

Note: Z index only works on positioned elements ( position:absolute , position:relative , or position:fixed ).


2 Answers

It doesn't work because you are applying a z-index to the parent element which makes the child element stack relative to the other elements within the parent.

Once you assign an element a value for z-index (other than auto), that element establishes its own local stacking context. This means that all of the element's descendants have their own stacking order, relative to the ancestor element.

So if the parent has z-index: 9 and the child is z-index: 8, it's kind of like assigning a z-index of 9, 8

See the article here for a better explanation.

If you remove the z-index on the parent and set the sibling element to z-index: -1, that should work. I'm not sure about all browsers, but it works in Chrome anyway.

Here is the updated fiddle

Hope that helps.

like image 86
fearofawhackplanet Avatar answered Oct 21 '22 16:10

fearofawhackplanet


You don't.

Instead, make the a be the "Sign In" "button".

Something like this: http://jsfiddle.net/5sqxQ/15/

like image 41
thirtydot Avatar answered Oct 21 '22 14:10

thirtydot