What's the best way to layer divs on top of on

2019-04-11 01:44发布

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?

2条回答
疯言疯语
2楼-- · 2019-04-11 01:56

Z-indexing in HTML5 works just as it always has. You will have to specify locations most likely but as for the layering itself, that's all automatic so long as you specify a z-index.

查看更多
男人必须洒脱
3楼-- · 2019-04-11 02:03
/*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;
查看更多
登录 后发表回答