为什么溢出与 z-index 交互?

新手上路,请多包涵

我试图了解 z-index 背后的规则以及它如何与溢出属性交互。

我有这个html:

 <body>
  <div class="cell">
    Here is some text to keep things interesting
    <div class="boxy"></div>
  </div>
</body>

这个CSS:

 .boxy {
  position: absolute;
  z-index: 9999;
  top:70px;
  width: 50px;
  height: 50px;
  background: #0FF;
}

.cell {
  border: 2px solid #F00;
  position: relative;

  /* comment these two lines out and the box appears */
  /* or change them both to 'visible' */
  /* changing only one of them to 'visible' does not work */
  overflow-y: auto;
  overflow-x: auto;
}

我原以为青色框会出现,即使它超出了 div.cell 的大小,因为它的 z-index 和它的位置已设置。

但是,使青色框出现的唯一方法是注释掉溢出-x 和-y 行。

我的问题是:如何使青色框出现在屏幕上,同时将溢出保持为隐藏或自动?但更重要的是,我希望了解 为什么 会发生这种情况。这里应用了哪些 CSS 和布局规则?

见我的 Plunkr。 这个例子当然是我实际使用的 HTML/CSS 的简化版本。


编辑 下面的答案似乎有些混乱,因为我解释得不够好。如果将两条溢出行注释掉,可以看到出现了青色框。它出现在 .cell 的边界之外。为什么会这样?如何使青色框出现,同时仍然隐藏溢出和 z-index?

原文由 Andrew Eisenberg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

青色框仅在 overflow-xoverflow-y 可见时出现,否则消失的原因,仅仅是因为青色框溢出了单元格框。 overflow: visible 简单的意思是“绘制这个框,即使它溢出了它的包含块”——单元格框是青色框的包含块,因为它的 position 是相对的。 overflow 的任何其他值都会导致溢出的内容从视图中被剪掉。这里没有什么特别的。特别是,z-index 是完全不相关的,并且没有问题标题所暗示的这种交互(而且真的没有理由将其设置为如此巨大的数字,除非您担心脚本会将其他元素注入单元格)。

在单元格有不可见溢出时允许出现青色框的唯一方法是从单元格中删除 position: relative 并将该声明应用于单元格的父级(在您的示例中,它是主体)。像这样:

 body {
  position: relative;
}

.boxy {
  position: absolute;
  z-index: 9999;
  top: 70px;
  width: 50px;
  height: 50px;
  background: #0FF;
}

.cell {
  border: 2px solid #F00;
  overflow: auto;
}
 <div class="cell">
  Here is some text to keep things interesting
  <div class="boxy"></div>
</div>

原文由 BoltClock 发布,翻译遵循 CC BY-SA 3.0 许可协议

父类 单元格 需要设置它的高度。因为 absolute 元素的高度不会影响它;它的父级。

  .boxy {
      position: absolute;
      z-index: 9999;
      top:70px;
      width: 50px;
      height: 50px;
      background: #0FF;

    }

    .cell {
      border: 2px solid #F00;
      position: relative;

      /* comment these two lines out and the box appears */
      /* or change them both to 'visible' */
      /* changing only one of them to 'visible' does not work */
      overflow-y: auto;
      overflow-x: auto;
      min-height: 120px; /* height 70px(Top)+50px*/
    }

原文由 Gautam Jha 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题