我有一个嵌套在z-index: 0
的元素内的元素,该元素位于z-index: 1
的元素下面。那个父元素*正确地**显示在另一个元素下面。但是,当我创建子元素display: table-cell; z-index: 2
时,它跳出它的父元素(在垂直的z轴上)并且在更高的外部元素之上!为什么会发生这种情况?如何阻止它?
示例:http://jsfiddle.net/5x8jy74o/
父作为display: table
的示例,同样的问题:http://jsfiddle.net/5x8jy74o/1/
HTML:
<div class="hover">
HOVER IN HERE
</div>
<div class="container">
<div class="tc">
This should be under
</div>
</div>
CSS:
.hover
{
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100px;
background-color: #e8e8e8;
z-index: 1;
}
.container
{
position: relative;
top: 0px;
left: 0px;
width: 100px;
height: 100px;
background-color: red;
}
.tc
{
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 50px;
background-color: blue;
display: table-cell;
z-index: 2;
}
答案 0 :(得分:2)
这与元素的display
table-cell
完全无关。
这是因为.container
元素实际上并非establishing a stacking context。尽管.container
元素相对定位,但它仍然默认z-index
为auto
,而不是0
。
如果要建立堆叠上下文,并阻止子元素出现在上一个兄弟上方,请添加z-index: 0
。否则.tc
将继续显示在.hover
上方,因为z-index
2
明显高于1
。
.container {
position: relative;
z-index: 0;
/* .. */
}