Elements not overlapping with z-index

4.5k views Asked by At

In my navigation I have a protruding red box. I want that red box to overlap all Divs bellow it. I set a margin for it so it would space it out among the other elements I put in the black box. The problem is that it's margin is also effecting the layout of separate elements' children bellow it. When I add a negative margin to the child elements of the section bellow it does overlap but I want the red box to be on-top. I use z-index and it doesn't seem to work.

Here's my example on Jsfiddle: http://jsfiddle.net/1qsuvhnd/29/

HTML

<nav>
    <div id="ribbon"></div>    
</nav>
<div id="context">
    <div class="link"></div>
</div>

CSS

#context {
    width: auto;
    padding: 20px;
    height: 300px;
    background-color: blue;
    z-index: 1;
}
#context .link {
    float: Left;
    height: 260px;
    width: 300px;
    margin-left: -140px;
    background-color: White;
    z-index:1 !important;
}
nav {
    width: auto;
    height: 65px;
    background-color: black;
    z-index:99 !important;
    clear:both;
}

nav #ribbon {
    float: left;
    margin: 0px 50px;
    Width: 65px;
    height: 130px;
    background-color: red;
    z-index= 99;
}
3

There are 3 answers

0
Arber Braja On

You need to specify a position CSS rule for the nav div for the z-index to work correctly, like this:

nav #ribbon {
    float: left;
    margin: 0px 50px;
    Width: 65px;
    height: 130px;
    background-color: red;
    z-index:99;
    position: relative;
}

Here is the new jsFiddle link: http://jsfiddle.net/1qsuvhnd/54/

0
Caio Kawasaki On

To use z-index, you need to specify a position (like absolute, fixed, or relative).

And the last line written is wrong:

z-index = 99;

The correct way to write it is:

z-index: 99;
0
docodemore On

How about: http://jsfiddle.net/1qsuvhnd/30/

change the ribbon to position: absolute; and fix the z-index = typo :D

Now you don't need that margin hack!!

nav #ribbon {
    float: left;
    margin: 0px 50px;
    Width: 65px;
    height: 130px;
    background-color: red;
    z-index: 99;   /* take that equal out and make it a colon */
    position: absolute;  /* position: absolute to the rescue!!!! */
}