CSS 優先級由 **4 位數字元組** 表示:(a, b, c, d)
style="") → 1 或 0比較規則:從左到右逐位比較,高者勝出。不進位(0,1,0,0 > 0,0,20,0)。
| 選擇器類型 | 權重 | 範例 |
|---|---|---|
| 內聯樣式 | (1,0,0,0) | <div style="color:red"> |
| ID 選擇器 | (0,1,0,0) | #header |
| 類選擇器 | (0,0,1,0) | .btn |
| 屬性選擇器 | (0,0,1,0) | [type="text"] |
| 偽類 | (0,0,1,0) | :hover, :nth-child(2) |
| 元素選擇器 | (0,0,0,1) | div, p |
| 偽元素 | (0,0,0,1) | ::before, ::after |
| 通用選擇器 | (0,0,0,0) | * |
| 組合子 | (0,0,0,0) | +, >, ~, |
:not() | 取內部最高權重 | :not(.foo) = (0,0,1,0) |
:is()/:where() | :is()取最高,:where()為 0 | :is(#id, .class) = (0,1,0,0) |
/* 權重計算 */
#nav .list > li.active a:hover
/* 分解:
#nav → (0,1,0,0)
.list → (0,0,1,0)
> → (0,0,0,0)
li → (0,0,0,1)
.active → (0,0,1,0)
a → (0,0,0,1)
:hover → (0,0,1,0)
總計 → (0,1,3,2)
*/
.forced { color: red !important; }
/* 優先級高於內聯樣式,僅次於瀏覽器用戶樣表 !important */
**避坑原則**:能不用就不用。僅用於:
• 第三方庫樣式覆蓋(且無法修改源碼)
• 全局工具類(.d-none { display: none !important; })
• 用戶自定義樣式表覆蓋
/* 父元素 */
.parent { color: blue; } /* 權重 (0,0,0,1) */
/* 子元素 */
.child { color: red; } /* 權重 (0,0,0,1) */
/* 繼承值權重為 0,任何顯式聲明(哪怕權重 0,0,0,0)都會覆蓋繼承值 */
.child { color: inherit; } /* 顯式繼承,權重 (0,0,0,0) 但勝過瀏覽器默認 */
.child { all: initial; } /* 重置所有屬性 */
/* :where() 永遠權重為 0,極易覆蓋 */
:where(.sidebar, .footer) a { color: inherit; }
/* :is() 取參數中最高權重 */
:is(#header, .nav) a { color: white; } /* 權重 (0,1,0,0) 來自 #header */
/* 實戰:重置組件內部優先級 */
.card :where(h1, h2, h3) { margin: 0; } /* 不提升優先級 */
優先級決定「哪條規則勝出」,層疊上下文決定「渲染順序」。兩者正交。
例:z-index: 9999 的元素若在 opacity: 0.5 的父級內,仍可能被父級外 z-index: 1 的元素覆蓋。
.a .b .c 已達 (0,0,2,1),再嵌套極難維護。CSS 優先級是**四元組比較系統**,非簡單加分。理解 (a,b,c,d) 算法、**!important 核彈機制**、**繼承值權重為 0**、現代 :where()/:is() 優先級控制,配合「無 ID、淺嵌套、BEM 扁平、工具類 !important」工程化規範,能從根源消除優先級戰爭,構建可預測、可維護的樣式系統。