Doubt on z-index on separate divs

1

I have the following code:

.div1{
    position: absolute;
    z-index:2;
}
.div2{
    position: absolute;
    z-index:1
}

The .div2 has an image that is above .div1 , some pixels only.

What happens is that in .div1 I have a dropdown menu that defaults to display:none , when I hover the mouse, it gets display:block and z-index: 3 , but this z-index does not stay above .div2 because it is inside .div1 that has z-index lower, have any solution for this?

    
asked by anonymous 17.06.2014 / 14:41

1 answer

4

z-index is an anthill. It is best to actually put the element that will stand on top of the outside. Put modals and prompts within <body> to avoid conflicts.

To better understand the reason for this problem, let's take a look at how z-index works:

Adapted from MDN :

  • Assigning a z-index value on an element creates a "stacking" context.
  • Stacking contexts may be contained in other contexts. Together they create a hierarchy of stacking contexts.
  • Each context is completely independent of its siblings: only descending elements are considered when stacking is processed.
  • Each stacking context is contained in itself: after the content of an element is stacked, the entire element is considered in the order of the stacking context of the parent.

It's complicated, is not it?

Let's take a look at this structure:

            z-index
div A       2
 |--div AA  1
 |--div AB  2

div B       1
 |--div BA  3
 |--div BB  4

In this scheme div A has z-index 2 and B has z-index 1. All divs within Div B will also have z-index 1 when compared to Div A and its daughter divs. The values 3 and 4 of BA and BB are only valid as they are in the same context (level).

One way to "break" the structure is to assign a negative value to the z-index of a daughter div, but note that this approach does not work in IE 6/7.

    
17.06.2014 / 16:57