层叠上下文的作用:
决定元素的显示顺序
产生层叠上下文的条件:
- html
- position(absolute/relative)且z-index不为auto
- position: fixed or sticky
- flex或者grid布局中,child项的z-index不为auto
- opacity:小于1
- mix-blend-mode:不为normal
- transform:不为none
- filter:不为none
- perspective:不为none
- clip-path:不为none
- mask / mask-image / mask-border:不为none
- isolation: isolate
- -webkit-overflow-scrolling: touch
- will-change
- contain: strict(layout、paint、size)/content(layout、paint)/layout/paint
层叠规则:
- background(color、iamge)、border
- z-index为负
- block元素
- float
- inline、inline-block元素
- z-index为auto、z-index为0
- 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. 兄弟之间遵守:后来居上的原则
参考资料
例子(MDN)
developer.mozilla.org/en-US/docs/…