| 類型 | 語法 | 匹配目標 | 優先級 |
|---|---|---|---|
| 通用 | * | 所有元素 | (0,0,0) |
| 類型/標籤 | E | 所有 E 元素 | (0,0,1) |
| 類別 | .class | class 包含指定值 | (0,1,0) |
| ID | #id | id 完全等於 | (1,0,0) |
| 類型 | 語法 | 關係 | 範例 |
|---|---|---|---|
| 群組 | E, F | E 或 F | h1, h2, .title |
| 後代 | E F | E 內所有 F(含孫代) | .article p |
| 子代 | E > F | E 直接子元素 F | .menu > li |
| 相鄰同層 | E + F | 緊鄰 E 後的 F | h2 + p |
| 一般同層 | E ~ F | E 後所有同層 F | h2 ~ p |
| 語法 | 匹配條件 | 範例 |
|---|---|---|
| [attr] | 擁有屬性 | a[target] |
| [attr=val] | 值完全等於 | input[type="email"] |
| [attr~=val] | 空格分隔值包含 | [class~="btn"] |
| [attr|=val] | 連字號分隔以 val 開頭 | [lang|="zh"] |
| [attr^=val] | 值以 val 開頭 | a[href^="https://"] |
| [attr$=val] | 值以 val 結尾 | a[href$=".pdf"] |
| [attr*=val] | 值包含 val | img[src*="avatar"] |
| [attr=val i] | 大小寫不敏感 (Level 4) | img[src$=".png" i] |
| [attr=val s] | 大小寫敏感 (Level 4) | data[value="ABC" s] |
:root, :empty
:first-child, :last-child, :only-child
:nth-child(n), :nth-last-child(n)
:first-of-type, :last-of-type, :only-of-type
:nth-of-type(n), :nth-last-of-type(n)
:link, :visited, :hover, :active, :focus, :focus-visible, :focus-within
:enabled, :disabled, :checked, :indeterminate
:valid, :invalid, :required, :optional
:in-range, :out-of-range
:read-only, :read-write
:placeholder-shown
:default
:lang(zh), :not(s), :is(s), :where(s), :has(s) (Level 4), :target
::before, ::after, ::first-line, ::first-letter
::selection, ::marker, ::placeholder, ::backdrop
::file-selector-button, ::grammar-error, ::spelling-error
四元組 (A, B, C, D):
style="" (1,0,0,0)比較規則:依序比較 A→B→C→D,高者勝出。相同則後寫者勝(就近原則)。
| 選擇器 | 權重 | 說明 |
|---|---|---|
| #header .nav > li.active a:hover | (0,1,3,3) | 1ID + 3Class/屬性/偽類 + 3標籤/偽元素 |
| .btn-primary:focus | (0,0,2,0) | 2Class/偽類 |
| div > p::first-line | (0,0,0,2) | 1標籤 + 1偽元素 |
| *:not(.foo) | (0,0,1,0) | :not 取參數最高權重 |
| :where(.foo, #bar) | (0,0,0,0) | :where 永遠 0 優先級 |
#id.classdivh1 + pul > lili a*[rel="external"]:hover, ::before⚠️ 現代瀏覽器選擇器匹配極快,優先級管理 > 微觀效能優化。重點避免:* { }、深層後代、通用屬性選擇器。
tag#id、tag.class(多餘標籤限定).nav-link 替代 .header .nav ul li a):where() 降低優先級(重置樣式、工具類):is() 簡化群組選擇器(:is(h1,h2,h3) a):not() 包含複雜選擇器精通選擇器後,建議學習 CSS 層分離架構(ITCSS/CUBE/BEM),從宏觀架構管控樣式複雜度。