Search code examples
htmlcssz-index

What's the best way to layer divs on top of one another in z-index?


I want to have some divs stacked on top of one another, but act otherwise like a normal div. I.e. I don't want to have to worry about manually positioning them. Is this possible in HTML5/CSS3?

For example:

<div id='outerDiv'>
    <div id='inner1' style='z-index: 1'>This should be the full size of outerDiv</div>
    <div id='inner2' style='z-index: 2'>This should appear overtop of inner1</div>
</div>

I hope there's a simple way to do this.

To put it another way, suppose I already have a page laid-out and perfect, but I want to take one already-positioned div and super-impose another div directly on top of it, exactly the same size, without screwing the existing layout up. Is this possible?


Solution

  • /*position relative as a base for non-static elements*/
    #outerDiv{
        position:relative;
    }
    
    /*every direct child positioned absolute*/
    #outerDiv > div {
        position:absolute;
    }
    

    at this time, they will be stacked on top of the other, with the more later element on top of the previous. if you want to force a previous div to be above the next, this is when you need to make its z-index explicitly higher than the next the #outerDiv will not stretch according to the children since it's taken out of the flow.


    if your #outerDiv has dimensions (width and height), and you want to stretch the children to it, then add to the children:

    //you might run into box model issues esp. if children have borders and padding
    height:100%;
    width:100%;
    

    or

    //this will contain paddings and borders, but i'm not sure what their side-effects are
    top:0;
    left:0;
    right:0;
    bottom:0;