在z-index中将div叠加在一起的最佳方法是什么?

问题描述 投票:3回答:2

我希望将一些div叠加在一起,但其他方式就像普通的div一样。即我不想担心手动定位它们。这可能在HTML5 / CSS3中吗?

例如:

<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>

我希望有一个简单的方法来做到这一点。

换句话说,假设我已经有一个布局和完美的页面,但我想要一个已经定位的div并且超级直接在它上面施加另一个div,完全相同的大小,而不用拧紧现有的布局起来。这可能吗?

html5 html css3 z-index
2个回答
10
投票
/*position relative as a base for non-static elements*/
#outerDiv{
    position:relative;
}

/*every direct child positioned absolute*/
#outerDiv > div {
    position:absolute;
}

在这个时候,它们将堆叠在另一个之上,后面的元素位于前一个之上。如果你想强迫前一个div高于下一个div,那么当你需要使它的z-index明显高于下一个时,#outerDiv将不会根据孩子伸展,因为它已被取出。


如果您的#outerDiv有尺寸(宽度和高度),并且您想要将孩子拉伸到它,那么添加到孩子:

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

要么

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

0
投票

HTML5中的Z-indexing就像它一直有效一样。您必须指定最有可能的位置,但对于分层本身,只要您指定z-index,这些都是自动的。

© www.soinside.com 2019 - 2024. All rights reserved.