【问题标题】:Why does a nested element of display table-cell show over a higher outer element?为什么显示表格单元格的嵌套元素会显示在更高的外部元素上?
【发布时间】:2015-12-09 21:41:20
【问题描述】:

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

【问题讨论】:

    标签: html css


    【解决方案1】:

    这与元素具有displaytable-cell 的事实完全无关。

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

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

    Updated Example

    .container {
      position: relative;
      z-index: 0;
    
      /* .. */
    }
    

    【讨论】:

    • 同样重要的是要注意display: table-cell; 与这里的堆叠没有任何关系。删除它并保留z-index 属性的工作方式相同:jsfiddle
    • 比你,这才是问题所在!我忘了给容器一个 z-index。
    猜你喜欢
    • 2019-09-02
    • 2011-05-07
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2017-09-18
    相关资源
    最近更新 更多