概念概述
CSS 级联层(CSS Cascade Layers)指的是:级联层让作者用显式的层顺序排列样式规则,使冲突由层的位置而非选择器权重决定,便于治理大规模样式。
从更严格的定义看,A cascade layer is a named grouping of CSS rules declared with the @layer rule, whose position in the layer order takes precedence over plain specificity when the cascade resolves a conflict. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。
为什么需要它
It is used to keep resets, frameworks, and application styles in predictable order without escalating specificity. 它与 CSS Container Queries、Third-Party Cookies and Storage Partitioning、Subresource Integrity (SRI) 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。
常见误解
- cascade layers change specificity scoring inside a selector
- an unlayered rule always loses to a layered rule
需要避免的反模式
- mixing layered and important declarations without a strategy
- relying on layer order while also fighting it with !important
实践要点
- The order in which layers are first declared establishes their precedence, and a rule inside an earlier layer loses to an equally specific rule in a later layer regardless of selector complexity.
- Unlayered styles sit in an implicit final layer that outranks declared layers, which lets legacy rules keep winning unless they are also placed into layers.
- Author important declarations invert the normal order across layers, so a small number of important rules can reintroduce the specificity problems layers were meant to remove.
参考来源
https://developer.mozilla.org/en-US/docs/Web/CSS/@layer
代码示例
@layer base, components, utilities;
@layer base {
h1 { font-size: 2rem; }
}
@layer components {
.btn { padding: 0.5rem 1rem; }
}
@layer utilities {
.mt-4 { margin-top: 1rem; }
}