为什么display table-cell的嵌套元素显示在更高的外部元素上?

时间:2015-12-09 21:41:21

标签: html css html5 css3

我有一个嵌套在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;
}

1 个答案:

答案 0 :(得分:2)

这与元素的display table-cell完全无关。

这是因为.container元素实际上并非establishing a stacking context。尽管.container元素相对定位,但它仍然默认z-indexauto,而不是0

如果要建立堆叠上下文,并阻止子元素出现在上一个兄弟上方,请添加z-index: 0。否则.tc将继续显示在.hover上方,因为z-index 2明显高于1

Updated Example

.container {
  position: relative;
  z-index: 0;

  /* .. */
}
相关问题