nightclub nightclub - 6 months ago 9
jQuery Question

z-index issue with two divs, one of them with absolute position

My question is very simple, I have two divs, one of them with absolute position. I set the z-index of the absolute position div to the lowest value and the other one with the highest value but always the one with absolute position remains on top (opposite behavior).

Here you have an image:

enter image description here

Here you have the code:

<div style="position:relative;">
<div style="position:absolute;width:200px;background-color:#ff0;z-index:1;">
SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
SHOULD BE ON BACK. SHOULD BE ON BACK.
</div>
<div style="width:300px;background-color:#0f0;z-index:999999;">
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
SHOULD BE ON FRONT. SHOULD BE ON FRONT.
</div>
</div>


Take a look at the following jsfiddle:

http://jsfiddle.net/rnbd3nek/

Answer

You need to get rid of the style in the parent div and add the style into the front div. Add position:relative to the 'THIS SHOULD BE ON FRONT'.

Thus:

<div>
    <div style="position:absolute;width:200px;background-color:#ff0;z-index:1;">
      SHOULD BE ON BACK. SHOULD BE ON BACK. SHOULD BE ON BACK.
    SHOULD BE ON BACK. SHOULD BE ON BACK. 
    </div>
    <div style="position:relative;width:300px;background-color:#0f0;z-index:999999;">
        SHOULD BE ON FRONT. SHOULD BE ON FRONT.
        SHOULD BE ON FRONT. SHOULD BE ON FRONT.
    </div>
</div>

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). -W3Schools, from here

Comments