利用 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/圖片作為虛線 | 極致視覺一致性需求 |
/* 強制渲染為虛線 */
a:hover {
border-bottom: 1px dotted;
/* 某舊版瀏覽器需加此 hack */
border-bottom: 1px dashed\9; /* IE8- hack */
}
a {
line-height: 1.5; /* 固定行高 */
padding-bottom: 2px; /* 微調底線距離文字的距離 */
border-bottom: 1px dotted currentColor; /* 繼承文字顏色 */
}
/* 使用 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; }CSS 實現連結虛線底線的核心在於 border-bottom + dotted/dashed + transition。進階需求可用偽元素配合漸變或 background-image 實現更豐富的動畫與多行支援。記得處理 :focus 狀態並注意跨瀏覽器一致性。