Why is overflow interacting with z-index?

瘦欲@ 提交于 2019-12-03 10:44:37

The reason the cyan box appears only when overflow-x and overflow-y are visible, and disappears otherwise, is simply because the cyan box is overflowing the cell box. overflow: visible simply means "paint this box even if it is overflowing its containing block" — the cell box is the containing block of the cyan box because its position is relative. Any other values of overflow cause overflowing content to be clipped from view. There is nothing special going on here; in particular, the z-index is completely irrelevant and there is no such interaction as the question title alludes to (and there really is no reason to set it to such a huge number unless you're worried about scripts injecting other elements into the cell).

The only way to allow the cyan box to appear while the cell has a non-visible overflow is to remove position: relative from the cell and apply that declaration to the parent of the cell (in your example, it's the body). Like this:

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>

Absolute-positioned elements do not contribute to the dimensions of their parents.

Therefore, the .cell DIV has no content that affects its dimensions, making it 100% wide by 0px high.

To make the element appear, you'll have to add a height to .cell that will encompass the DIV, in this case 120px (70px top + 50px height).

The Parent Class cell need to be set it's height. because height of absolute element doesn't affect it;s parent.

 .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*/
    }

Your problem

Your problem is related to cell node that hides boxy when overflow is specified on cell node.

The reason

The reason behind is that boxy with position absolute does not contribute to height of cell and overflow hides it.

Why is it shown without overflow?

By default overflow is visible, which for browser means do not do anything special for overflow functionality and it does not need to render overflow => does not hide boxy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!