Why is overflow interacting with z-index?

前端 未结 4 1755
挽巷
挽巷 2021-02-12 20:28

I am trying to understand the rules behind z-index and how it interacts with the overflow property.

I have this html:


  
4条回答
  •  深忆病人
    2021-02-12 21:35

    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;
    }
    Here is some text to keep things interesting

提交回复
热议问题