Html 在 z-index 中将 div 层叠在一起的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9730752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to layer divs on top of one another in z-index?
提问by devios1
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?
我想将一些 div 堆叠在一起,但在其他方面像普通 div 一样。即我不想担心手动定位它们。这在 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?
换句话说,假设我已经有一个页面布局和完美,但我想拿一个已经定位的 div 并直接在它上面叠加另一个 div,完全相同的大小,而不是搞砸现有的布局向上。这可能吗?
回答by Joseph
/*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.
此时,它们将堆叠在另一个之上,后面的元素位于前一个之上。如果你想强制前一个 div 高于下一个,这是当你需要z-index
明确地使其高于下一个时,#outerDiv
不会根据孩子的情况进行拉伸,因为它被从流程中取出。
if your #outerDiv
has dimensions (width and height), and you want to stretch the children to it, then add to the children:
如果您#outerDiv
有尺寸(宽度和高度),并且您想将孩子拉伸到它,然后添加到孩子:
//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;
回答by Marc H
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.
HTML5 中的 Z 索引就像往常一样工作。您最有可能必须指定位置,但至于分层本身,只要您指定 z-index,这一切都是自动的。