ALN90
ALN90

Reputation: 51

z-index not working when using negative margins

I am having an issue with z-index stacking. The below div is appearing over the top of the top div even when z-index and positions state the below div should be under the div above it.

I have provided a JSFiddle of an example with the code that I am using.

https://jsfiddle.net/6hewonhb/

.above-box {
    padding-left: 50px;
    padding-right: 50px;
    padding-top: 20px;
    padding-bottom: 20px;
    background: rgba(251, 47, 111, 0.2);
    color: #fff;
    z-index: 10 !important;
    position: relative !important;
    margin-top: 0px !important;
    margin-right: 0px !important;
    margin-left: 0px !important;
    height: 100px;
    width: 100px;
}

.below-box {
    margin-top: -20px !important;
    margin-left: 70px !important;
    position: relative !important;
    z-index: 5 !important;
    background-color: #f00;
    height: 100px;
    width: 100px;
}
<div class="above-box">
    TEST
</div>

<div class="below-box">
    TEST
</div>

Upvotes: 0

Views: 2314

Answers (1)

Nutshell
Nutshell

Reputation: 8537

It is actually working. Be careful about your RGBA values of the .above-box div.

The fourth value is the opacity parameter, here opacity is set to 1 :

background:rgba(251,47,111,1);

See this fiddle

Besides, it is not needed to add !important; almost everywhere in the CSS code.

EDIT : For your issue, please double check positions of each of these elements in the DOM before adding z-index property. z-index property works fine with elements which are in the same level in DOM document.

Like this example

Also, you can read this very good explanation of z-index on this post : Z-Index Relative or Absolute?

Hope that helps.

Upvotes: 2

Related Questions