层叠上下文是一个独立的渲染上下文,它控制着其子元素的层叠顺序。创建层叠上下文的常见方式包括:
<html> 元素)。relative、absolute、fixed 或 sticky 且 z-index 值不为 auto 的元素。opacity 值小于 1。transform、filter、perspective、clip-path 等属性的元素。will-change 指定这些属性的元素。在同一层叠上下文中,元素的层叠顺序由以下规则决定(从低到高):
背景和边框(Background and Borders):
负 z-index 的后代(Negative Z-index Descendants):
块级格式化上下文的子元素(Block-level Descendants):
浮动元素(Floats):
float: left; 或 float: right;)排在普通文档流元素之上。内联元素和内联块元素(Inline and Inline-block Elements):
z-index: auto 或 z-index: 0 的后代(Z-index: Auto or Z-index: 0 Descendants):
auto 或 0 的定位元素。正 z-index 的后代(Positive Z-index Descendants):
假设有以下 HTML 结构:
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
</div>
对应的 CSS:
.parent {
position: relative;
z-index: 1;
}
.child1 {
position: absolute;
z-index: 2;
}
.child2 {
position: absolute;
z-index: 3;
}
.child3 {
position: absolute;
z-index: 1;
}
在这个例子中,.parent 元素创建了一个新的层叠上下文。child2 的 z-index 最大,因此它会覆盖其他子元素,而 child3 和 child1 的 z-index 分别为 1 和 2,所以 child1 会覆盖 child3。
理解层叠顺序和层叠上下文对于正确地管理网页元素的显示层级非常关键。在设计和开发中,使用适当的 z-index 值以及理解如何创建和管理层叠上下文,可以避免样式和显示问题。