FE Interview Hub
CSS基礎

請說明 CSS 選擇器的優先級

AI 練習作答

CSS 選擇器優先級(Specificity)

CSS 優先級決定了當多條規則套用在同一個元素時,哪條規則最終生效。

優先級由高到低

等級 類型 範例
最高 !important color: red !important
1000 Inline style style="color: red"
100 ID 選擇器 #header
10 Class、屬性、偽類 .btn[type="text"]:hover
1 元素、偽元素 pdiv::before
0 通用選擇器 *

計算方式

優先級以 (a, b, c) 三位數表示:

  • a:ID 選擇器數量
  • b:Class / 屬性 / 偽類數量
  • c:元素 / 偽元素數量
/* (0, 0, 1) = 1 */
p { color: red; }

/* (0, 1, 0) = 10 */
.text { color: blue; }

/* (1, 0, 0) = 100 */
#title { color: green; }

/* (1, 1, 1) = 111 */
#title .text p { color: purple; }

常見陷阱

  • 相同優先級時,後定義的規則勝出
  • !important 強制覆蓋所有規則,應避免濫用
  • :not() 偽類本身不計分,但括號內的選擇器會計分

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分