瀏覽器自帶的 text-decoration: underline 樣式實在稱不上好看:線條粗細、與文字的間距都無法調整。想做出精緻一點的下劃線,最簡潔的辦法是把線條畫成一張小圖,再用背景定位貼在文字底下。
把相關屬性集中寫在 a 上:
a {
text-decoration: none;
background: url(underline.gif) repeat-x 100% 100%;
padding-bottom: 4px;
white-space: nowrap;
}
幾個細節值得說明。repeat-x 100% 100% 讓細線沿水平方向平鋪、並貼齊元素右下角,因此不論文字多長都能完整覆蓋;padding-bottom: 4px 決定線條與文字之間的呼吸空間;white-space: nowrap 則是為了避免換行時背景圖被切得零零碎碎。
如果希望預設乾淨、游標移上去才浮現下劃線,把背景相關的宣告搬到 :hover 偽類裡就好:
a {
text-decoration: none;
padding-bottom: 4px;
white-space: nowrap;
}
a:hover {
background: url(underline.gif) repeat-x 100% 100%;
}
這招的彈性在於你可以把 underline.gif 換成漸層、虛線、雙線甚至小圖案,完全不受 text-decoration 那幾種單調樣式的限制。