層疊特性:解決**同一元素**多條 CSS 規則衝突的優先級算法。
繼承:子元素自動獲得**父元素**特定屬性的計算值。
兩者本質不同,切勿混淆。
| 等級 | 來源 | 權重 | 例子 |
|---|---|---|---|
| A | 行內樣式 style="" | 1,0,0,0 | <div style="color:red"> |
| B | ID 選擇器 | 0,1,0,0 | #header |
| C | 類別/屬性/偽類 | 0,0,1,0 | .btn, [type="text"], :hover |
| D | 元素/偽元素 | 0,0,0,1 | div, ::before |
| 通配符 | * | 0,0,0,0 | 無專一性 |
**比較規則**:從左到右比較,左邊大者勝出,不進位 (0,1,0,0 > 0,0,10,10)。
<p id="text" class="highlight" style="color: orange;">文字</p>
/* CSS */
p { color: green; } /* 0,0,0,1 */
.highlight { color: red; } /* 0,0,1,0 */
#text { color: blue; } /* 0,1,0,0 */
style="..." { color: orange; } /* 1,0,0,0 */
/* 最終顏色:orange (行內樣式勝出) */
.a { color: red; }
.b { color: blue; }
<p class="a b">藍色</p> /* .b 寫在後面,勝出 */
<p class="b a">藍色</p> /* 類別順序不影響,CSS 宣告順序決定 */
.force-red { color: red !important; }
.visually-hidden)。元素滿足任一條件即建立**層疊上下文**,內部元素的 z-index 僅在該上下文內比較,不參與外部比較:
<html>position: relative/absolute/fixed/sticky + z-index ≠ autoopacity < 1transform/filter/perspective/clip-path/mask ≠ noneisolation: isolatewill-change 指定上述屬性contain: layout/paint<div class="parent" style="z-index: 1;">
<div class="child" style="z-index: 9999;">我被遮住了</div>
</div>
<div class="sibling" style="z-index: 2;">我遮住 child</div>
.parent 建立層疊上下文,.child 的 9999 僅在 .parent 內比較,.parent (z-index:1) 輸給 .sibling (z-index:2)。
getMatchedCSSRules() (已棄用) / CSS.escape() 輔助。.u-color-red 替代。@layer reset, base, components, utilities; 以層級而非專一性管理優先權。層疊特性是 CSS 級聯的核心邏輯。掌握四元組計算、層疊上下文機制、現代 @layer 用法,才能駕馭大型專案的樣式架構。更多 CSS 架構進階,請關注本站工程化專題。