CSS 偽選擇器用於定義元素在特定狀態下的樣式,最常見的是超連結(<a>)的四種狀態:
<style type="text/css">
a:link { color: #FF0000; } /* 正常未訪問狀態 */
a:visited { color: #0000FF; } /* 已訪問狀態 */
a:hover { color: #00FF00; } /* 滑鼠懸停狀態 */
a:active { color: #FF00FF; } /* 點擊按下瞬間 */
</style>
請嘗試互動下方連結觀察顏色變化:
為避免樣式被覆蓋,必須遵循 LoVe HAte 順序:
:link:visited:hover:active錯誤順序會導致 hover/active 樣式失效。
| 選擇器 | 說明 | 範例 |
|---|---|---|
:focus | 元素獲得焦點 | input:focus { border-color: blue; } |
:first-child | 父元素第一個子元素 | li:first-child { font-weight: bold; } |
:nth-child(n) | 第 n 個子元素 | tr:nth-child(odd) { background: #f0f0f0; } |
:before / :after | 插入內容 | .clearfix:after { content: ""; display: table; clear: both; } |
:not(selector) | 排除符合選擇器 | input:not([type="submit"]) { width: 100%; } |