0

.header {
    background-color: #f1f1f1;
    position: fixed;
    top:0;
    width:100%; 
}

.header p {
    padding: 15px 15px;
    font-size: 20px;
    display: inline-block;
}

.header a {
    text-decoration: none;
    color: #111;
    background-color: #ddd;
    padding: 5px 10px;
    box-shadow: 0 0 2px darkgray;
}

.header p:nth-child(2) {
    position: absolute;
    left:0;
    right:0;
    text-align: center;
    z-index: -1;
    background-color: red;
}
<div class="header"> 
    <p><a href="#">Something</a></p>
    <p>something two</p>
</div>

I have a parent with position fixed, and two child-elements. One is position absolute, and made to take the entire width thus covering its sibling. When I use z-index -1, the element goes beneath the sibling, not not beneath the parent.

However, if I make the parent position relative or absolute, instead of fixed, now the child-element with z-index -1 goes beneath the parent as well.

.header {
    background-color: #f1f1f1;
    position: absolute;
    top:0;
    width:100%; 
}

.header p {
    padding: 15px 15px;
    font-size: 20px;
    display: inline-block;
}

.header a {
    text-decoration: none;
    color: #111;
    background-color: #ddd;
    padding: 5px 10px;
    box-shadow: 0 0 2px darkgray;
}

.header p:nth-child(2) {
    position: absolute;
    left:0;
    right:0;
    text-align: center;
    z-index: -1;
    background-color: red;
}
<div class="header"> 
    <p><a href="#">Something</a></p>
    <p>Something two</p>
</div>

I know this has something to do with the fact that, fixed is relative to the viewport, because same thing happens with sticky as well, but I would appreciate if someone explains what exactly is happening.

0 Answers0