Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a child element behind his parent element with z-index

I would like to know if it possible to have a child element behind his parent element with z-index.

I would like to use the parent div as transparent color layer on top of his content.

like image 964
Roch Avatar asked Sep 01 '10 09:09

Roch


People also ask

Can a child element have a higher z index than parent?

This is impossible as a child's z-index is set to the same stacking index as its parent. You have already solved the problem by removing the z-index from the parent, keep it like this or make the element a sibling instead of a child.

Do child elements inherit Z index?

No, it isn't inherited.

Is Z index relative to parent?

The z-index of elements inside of a stacking context are always relative to the parent's current order in its own stacking context.


1 Answers

Why not? Sure you can, and it's easy:

  1. give a non-static position to your desired elements;
  2. set z-index of child to -1;
  3. create a stacking context on the main container (by setting on it a z-index, opacity, transforms or whatelse generates a composite layer).

.container {
    position: absolute;
    z-index: 0; /* or eg. opacity: 0.99;*/
  
    background-color: blue;
    color: lightblue;
    width: 100%;
    height: 100%;
    text-align: center;
}

.parent {
    position: relative;
  
    background-color: rgba(100, 255, 150, 0.75);
    color: green;
    width: 50%;
    height: 30%;
    top: 30%;
    left: 20%;
}

.child {
    position: absolute;
    z-index: -1;
  
    background-color: orange;
    color: yellow;
    width: 100%;
    height: 100%;
    top: -50%;
    left: 20%;
}
<div class="container">
    <span>container</span>
    <div class="parent">
        <span>parent</span>
        <div class="child">
            <span>child</span>
        </div>
    </div>
</div>

(if the parent is used as a transparent layer, be sure to use a background-image or rgba background-color: children inherit the opacity of the parent)

like image 141
guari Avatar answered Nov 15 '22 16:11

guari