萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 超鏈接樣式完全控制指南:四狀態順序、三種作用域、現代偽類與無障礙增強

四大偽類順序鐵律:LVHA(Love Hate)

a:link    { color: #0066cc; }      /* 未訪問 */
a:visited { color: #663399; }      /* 已訪問 — 隱私限制僅可改色相關屬性 */
a:hover   { color: #ff3300; text-decoration: underline; }  /* 懸停 */
a:active  { color: #cc0000; }      /* 按下瞬間 */

/* 現代增強:鍵盤聚焦可見性 */
a:focus { outline: 2px solid #0066cc; outline-offset: 2px; }
a:focus:not(:focus-visible) { outline: none; }  /* 僅鍵盤導航顯示 */

順序錯誤後果: 後聲明覆蓋前聲明,導致已訪問/懸停/按下狀態失效。

三種作用域控制策略

1. 全局基線 — Reset/Normalize 階段

a {
  color: inherit;           /* 繼承父級文字色 */
  text-decoration: none;    /* 去底線 */
  text-underline-offset: 2px; /* 現代底線間距 */
}
a:hover { text-decoration: underline; }

2. 組件作用域 — BEM / 模塊化 CSS

.nav { }
.nav__link { color: #333; }
.nav__link:hover { color: #007bff; }
.nav__link--active { font-weight: 600; }

/* 使用 */
<nav class="nav">
  <a class="nav__link" href="/">首頁</a>
  <a class="nav__link nav__link--active" href="/about">關於</a>
</nav>

3. 工具類 — 原子化/Utility-first

.link { color: inherit; text-decoration: none; }
.link:hover { text-decoration: underline; }
.link--primary { color: var(--color-primary); }
.link--muted { color: var(--color-muted); }
<a class="link link--primary" href="#">主要鏈接</a>
<a class="link link--muted" href="#">次要鏈接</a>

進階偽類與選擇器

偽類觸發條件典型用途
:any-link匹配所有有 href 的 <a>統一鏈接基線樣式
:local-link指向當前源的鏈接(草案)高亮當前頁導航
:targetURL hash 指向的元素錨點高亮、模態框
:focus-visible鍵盤聚焦時無障礙聚焦環
:hover + :not(:focus-visible)僅鼠標懸停區分鼠標/鍵盤樣式

屬性選擇器精準匹配

/* 外部鏈接自動加圖標 */
a[href^="http"]:not([href*="mydomain.com"])::after {
  content: " ↗"; margin-left: 4px; font-size: 0.8em;
}

/* 文件下載鏈接 */
a[href$=".pdf"]::before { content: "📄 "; }
a[href$=".zip"]::before { content: "📦 "; }

/* 郵件/電話 */
a[href^="mailto:"]::before { content: "✉️ "; }
a[href^="tel:"]::before { content: "📞 "; }

無障礙(a11y)檢查清單

  • ✅ 可見焦點指示器(:focus-visible)
  • ✅ 足夠對比度(WCAG AA 4.5:1,大字 3:1)
  • ✅ 可辨識鏈接文本(避免「點擊這裡」「更多」)
  • ✅ 外部鏈接提示新窗口/域名(aria-label 或視覺圖標)
  • ✅ target="_blank" 必配 rel="noopener noreferrer"
  • ✅ 跳過鏈接:頁面頂部 ``

現代重置建議

/* 現代鏈接重置 */
a {
  color: inherit;
  text-decoration: none;
  text-underline-offset: 0.15em;
  text-decoration-thickness: 0.1em;
}
a:hover, a:focus-visible {
  text-decoration: underline;
}
a:focus:not(:focus-visible) { outline: none; }
a[href] { cursor: pointer; }  /* 確保無 href 的 a 不顯示手型 */

超鏈接是 Web 的靈魂。精心設計的鏈接樣式系統,不僅關乎美觀,更是用戶導航效率、無障礙合規、品牌一致性的基石。

copyright © 萬盛學電腦網 all rights reserved