萬盛學電腦網

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

CSS 實現連結虛線底線效果:hover 狀態下的邊框動畫技巧

核心原理

利用 border-bottom 替代 text-decoration: underline,配合 dotted 或 dashed 樣式,並在 :hover 狀態下顯示,實現優雅的虛線底線動畫效果。

基礎實現代碼

/* 連結預設狀態:無底線 */
a {
  color: #3399ff;
  font-weight: normal;
  text-decoration: none;          /* 關鍵:移除預設底線 */
  border-bottom: 1px solid transparent; /* 佔位防止跳動 */
  transition: border-color 0.3s, color 0.3s;
}

/* Hover 狀態:顯示虛線底線 */
a:hover {
  color: #4499ee;
  border-bottom: 1px #0099cc dotted;  /* 虛線底線 */
  /* 或使用 dashed 獲取虛線 */
}

進階版:動畫虛線底線(從中間展開)

.animated-link {
  position: relative;
  color: #2c3e50;
  text-decoration: none;
  padding-bottom: 4px;
}

.animated-link::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 0;
  height: 2px;
  background: repeating-linear-gradient(
    90deg,
    #3498db,
    #3498db 4px,
    transparent 4px,
    transparent 8px
  );
  transition: width 0.3s ease, left 0.3s ease;
}

.animated-link:hover::after {
  width: 100%;
  left: 0;
}

此方案使用 repeating-linear-gradient 繪製虛線,配合偽元素寬度動畫,效果更流暢且可控性更強。

虛線樣式對比

屬性值視覺效果適用場景
dotted圓點狀,間距較小輕量級提示、底線裝飾
dashed方塊狀,間距較大分隔線、編輯狀態指示
repeating-linear-gradient完全可控(長度、間距、顏色、圓角)品牌化設計、複雜動畫
border-image使用 SVG/圖片作為虛線極致視覺一致性需求

常見問題與解決方案

問題 1:虛線在某些瀏覽器顯示為實線

/* 強制渲染為虛線 */
a:hover {
  border-bottom: 1px dotted;
  /* 某舊版瀏覽器需加此 hack */
  border-bottom: 1px dashed\9; /* IE8- hack */
}

問題 2:文字行高導致虛線位置偏移

a {
  line-height: 1.5;           /* 固定行高 */
  padding-bottom: 2px;        /* 微調底線距離文字的距離 */
  border-bottom: 1px dotted currentColor; /* 繼承文字顏色 */
}

問題 3:多行連結底線只出現在最後一行

/* 使用 text-decoration-skip-ink (現代瀏覽器) */
a:hover {
  text-decoration: underline dotted;
  text-underline-offset: 4px;
  text-decoration-skip-ink: auto;
}

/* 或使用 background-image 模擬每行底線 */
a.multiline-link {
  background-image: repeating-linear-gradient(
    90deg,
    currentColor,
    currentColor 2px,
    transparent 2px,
    transparent 6px
  );
  background-position: 0 1.2em;
  background-repeat: repeat-x;
  background-size: 8px 1px;
  padding-bottom: 4px;
}

無障礙考量

  • 確保 :focus 狀態同樣有明顯底線:a:focus { border-bottom-style: dotted; }
  • 顏色對比度需符合 WCAG AA 標準(至少 4.5:1)。
  • 避免僅靠顏色區分狀態,結合底線樣式變化。

總結

CSS 實現連結虛線底線的核心在於 border-bottom + dotted/dashed + transition。進階需求可用偽元素配合漸變或 background-image 實現更豐富的動畫與多行支援。記得處理 :focus 狀態並注意跨瀏覽器一致性。

copyright © 萬盛學電腦網 all rights reserved