給文字加下劃線看似簡單,實則有 text-decoration、border-bottom、偽元素三大技術路線,各有優劣。本文系統對比三種方案的能力邊界、瀏覽器支援、無障礙表現,助你按需選擇。
| 特性 | text-decoration | border-bottom | 偽元素 ::after |
|---|---|---|---|
| 線型 | solid, double, dotted, dashed, wavy | solid, double, dotted, dashed, groove, ridge, inset, outset | 任意(漸變、圖片、SVG、動畫) | 顏色 | text-decoration-color(可與文字色分離) | border-color(獨立控制) | 完全自由 |
| 距離控制 | text-underline-offset | padding-bottom | bottom / transform |
| 粗細控制 | text-decoration-thickness | border-width | 完全自由 |
| 換行行為 | 每行獨立底線(原生) | 每行獨立底線 | 需 box-decoration-break: clone 或 display:inline-block |
| 瀏覽器支援 | 現代瀏覽器全支援(IE 不支援新屬性) | 全瀏覽器(IE6+) | 全瀏覽器(IE9+ 偽元素) |
| 無障礙/語意 | 最佳(原生語意) | 良好 | 需 ARIA 輔助 |
| 動畫/過渡 | 支援色/粗/距離動畫 | 支援色/粗/樣式動畫 | 最豐富(寬度展開、漸變移動等) |
.underline-basic {
text-decoration: underline;
/* 現代增強屬性 */
text-decoration-color: #667eea; /* 線條顏色 */
text-decoration-style: wavy; /* solid | double | dotted | dashed | wavy */
text-decoration-thickness: 2px; /* 線條粗細 */
text-underline-offset: 4px; /* 與文字距離 */
/* 簡寫 */
text-decoration: underline 2px wavy #667eea;
text-underline-offset: 4px;
}
.link-modern {
text-decoration: underline;
text-decoration-color: #ccc;
text-underline-offset: 3px;
transition: text-decoration-color 0.2s, text-decoration-style 0.2s;
}
.link-modern:hover {
text-decoration-color: #667eea;
text-decoration-style: solid;
}
⚠️ IE/舊版 Edge 不支援 text-decoration-color/style/thickness/offset,需降級或用 PostCSS 插件自動轉換。
.underline-border {
text-decoration: none; /* 移除原生 */
border-bottom: 1px solid #333; /* 線條樣式 */
padding-bottom: 2px; /* 距離控制 */
color: #333; /* 文字顏色 */
}
/* 文字紅、底線藍 */
.underline-color-split {
border-bottom: 2px solid #00f;
color: #c00;
}
.dashed { border-bottom: 1px dashed #666; }
.dotted { border-bottom: 1px dotted #666; }
.double { border-bottom: 3px double #666; }
.underline-pseudo {
text-decoration: none;
position: relative;
padding-bottom: 4px;
}
.underline-pseudo::after {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 2px;
background: #667eea;
}
.underline-slide::after {
transform: scaleX(0);
transform-origin: right;
transition: transform 0.3s cubic-bezier(0.25, 1, 0.5, 1);
}
.underline-slide:hover::after {
transform: scaleX(1);
transform-origin: left;
}
.underline-gradient::after {
background: linear-gradient(90deg, #667eea, #764ba2, #f093fb);
background-size: 200% 100%;
animation: gradient-flow 3s linear infinite;
}
@keyframes gradient-flow {
to { background-position: -200% 0; }
}
/* 方案:box-decoration-break: clone (現代) */
.underline-break {
-webkit-box-decoration-break: clone;
box-decoration-break: clone; /* border-bottom、偽元素在換行處各自繪製 */
}
/* 方案:inline-block 強制不換行(不推薦長文) */
.underline-nowrap { display: inline-block; }
總結:現代專案建議**預設使用 text-decoration 系列**,語意正確、代碼最少、無障礙最佳;相容性受限時退回 border-bottom;極致視覺效果用偽元素。三種方案可組合:基礎語意用 text-decoration,Hover 增強用偽元素動畫。