层叠上下文

234 阅读1分钟

层叠上下文的作用:

决定元素的显示顺序

产生层叠上下文的条件:

  1. html
  2. position(absolute/relative)且z-index不为auto
  3. position: fixed or sticky
  4. flex或者grid布局中,child项的z-index不为auto
  5. opacity:小于1
  6. mix-blend-mode:不为normal
  7. transform:不为none
  8. filter:不为none
  9. perspective:不为none
  10. clip-path:不为none
  11. mask / mask-image / mask-border:不为none
  12. isolation: isolate
  13. -webkit-overflow-scrolling: touch
  14. will-change
  15. contain: strict(layout、paint、size)/content(layout、paint)/layout/paint

层叠规则:

  1. background(color、iamge)、border
  2. z-index为负
  3. block元素
  4. float
  5. inline、inline-block元素
  6. z-index为auto、z-index为0
  7. z-index为正
    (摘自mdn,比较好理解)
    1. The background and borders of the root element
    2. Descendant non-positioned blocks, in order of appearance in the HTML
    3. Floating blocks
    4. Descendant non-positioned inline elements
    5. Descendant positioned elements, in order of appearance in the HTML

ps: 1. 子元素的层叠顺序受限于父元素 2. 兄弟之间遵守:后来居上的原则

参考资料

层叠上线文

z-index

float元素的层叠

opacity的层叠

深入理解CSS中的层叠上下文和层叠顺序

例子(MDN)

developer.mozilla.org/en-US/docs/…

developer.mozilla.org/en-US/docs/…

developer.mozilla.org/en-US/docs/…