超連結(<a>)有四種狀態偽類,正確順序與樣式定義能提升使用者體驗。本文詳細說明 LVHA 順序原理、各偽類用途與實用樣式範例。
| 偽類 | 觸發時機 | 典型用途 |
|---|---|---|
:link | 未造訪過的連結 | 預設連結顏色、底線 |
:visited | 已造訪過的連結 | 區分已讀,通常降低飽和度 |
:hover | 滑鼠懸停時 | 視覺回饋(變色、底線、放大) |
:active | 滑鼠按下未放開瞬間 | 按下狀態(縮放、陰影、顏色反轉) |
CSS 選擇器優先序相同時,**後定義者勝出**。若順序錯誤(如 :hover 在 :visited 前),已造訪連結的 hover 效果會被覆蓋失效。記憶口訣:**L**o**V**e **H**ate **A**pple。
a:link { color: #1976d2; text-decoration: none; }
a:visited { color: #7b1fa2; }
a:hover { color: #1565c0; text-decoration: underline; }
a:active { color: #0d47a1; background: #e3f2fd; }
/* 現代寫法:合併 link/visited */
a { color: #1976d2; text-decoration: none; }
a:visited { color: #7b1fa2; }
a:hover { color: #1565c0; text-decoration: underline; }
a:active { color: #0d47a1; }
a:focus { outline: 2px solid #1976d2; outline-offset: 2px; }
a:focus:not(:focus-visible) { outline: none; }
a:focus-visible { outline: 2px solid #1976d2; outline-offset: 2px; }
鍵盤導航時必須有明顯焦點指示,:focus-visible 讓滑鼠點擊不顯示外框,鍵盤聚焦才顯示。
.btn-link {
display: inline-block; padding: .5rem 1rem;
background: #1976d2; color: #fff; border-radius: .25rem;
text-decoration: none; transition: .2s;
}
.btn-link:hover { background: #1565c0; transform: translateY(-1px); }
.btn-link:active { background: #0d47a1; transform: translateY(0); }