Search code examples
htmlcsspositionz-index

Why z-index doesnt work?


I have simple html and css code :

HTML:

<div class="header">
    <div class="tip"></div>
</div>

CSS:

.header {
    display: block;
    width: 260px;
    min-height: 222px;
    background-color: #252525;
    position: relative;
    z-index: 5;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;
    border-radius: 2px;
}
.tip {
    display: inline-block;
    width: 10px;
    height: 10px;
    right: 11px;
    top: -5px;
    transform: rotateZ(45deg);
    position: absolute;
    z-index: 1;
    background-color: red;
    -webkit-box-shadow: 0 0 5px #000;
    -moz-box-shadow: 0 0 5px #000;
    box-shadow: 0 0 5px #000;

}

I just want to .tip block was under .header block. But now it looks like this, although the z-index of .tip is less then z-index of .header: enter image description here

This is what I want: enter image description here

For some reason, z-index doesn't work. It's necessary for me to set z-index on .header block, because I have another blocks on page which have z-index too


Solution

  • To make the child of a parent element have a higher z-index than the parent element, remove the parent's z-index value.

    .header {
        display: block;
        width: 260px;
        min-height: 222px;
        background-color: #252525;
        position: relative;
        /*z-index: 5;*/
        -webkit-box-shadow: 0 0 5px #000;
        -moz-box-shadow: 0 0 5px #000;
        box-shadow: 0 0 5px #000;
        border-radius: 2px;
    }
    .tip {
        display: inline-block;
        width: 10px;
        height: 10px;
        right: 11px;
        top: -5px;
        transform: rotateZ(45deg);
        position: absolute;
        z-index: -1;
        background-color: red;
        -webkit-box-shadow: 0 0 5px #000;
        -moz-box-shadow: 0 0 5px #000;
        box-shadow: 0 0 5px #000;
    }
    <div class="header">
        <div class="tip"></div>
    </div>