偽類讓 CSS 能選中「文檔樹結構無法表達」的狀態:鏈接訪問狀態、滑鼠交互狀態、首個子元素等。掌握偽類是寫出精準、可維護樣式的關鍵。
/* 基礎偽類 */
selector:pseudo-class { property: value; }
/* 結合類名 */
selector.class:pseudo-class { property: value; }
/* 例:所有鏈接紅色,類為 c1 的鏈接綠色 */
a:link { color: red; }
a.c1:link { color: green; }
a:link { color: #FF0000; } /* 未訪問 */
a:visited { color: #00FF00; } /* 已訪問 */
a:hover { color: #FFCC00; } /* 滑鼠懸停 */
a:active { color: #0000FF; } /* 點擊激活 */
⚠️ 必須按 L-V-H-A 順序書寫,否則後定義的樣式會覆蓋前者(同權重下後勝出)。記憶口訣:**LoVe HAte**。
a.c1:link { color: #FF0000; }
a.c1:visited { color: #00FF00; }
a.c1:hover { color: #FFCC00; }
a.c1:active { color: #0000FF; }
a:focus, a:hover { outline: 2px solid #09f; }/* 首個 li 無左邊框 */
.nav li:first-child { border-left: none; }
/* 最後項右圓角 */
.card:last-child { border-radius: 0 8px 8px 0; }
/* 隔行變色 */
tbody tr:nth-child(odd) { background: #f9f9f9; }
IE9+ 完整支援,IE8 僅支援 `:first-child`。
雙冒號區分偽元素(CSS3 規範),單冒號兼容舊瀏覽器。常用於:
.clearfix::after { content:""; display:table; clear:both; }💡 核心心法:偽類選「狀態」,偽元素造「內容」。LVHA 順序不變,結構性偽類減少 HTML 類名污染。