CSS 本身沒有提供「更換 HTML 連結下劃線樣式」的指令,但只要繞個路,用背景圖去模擬,下劃線就能變成波紋、花朵,甚至任何你畫得出來的圖案。
第一步:準備圖形。做一張小圖,沿水平方向重複排列後就形成一條下劃線。若想讓下劃線底下透出網頁背景,請存成透明的 .gif。
第二步:預留行距。如果下劃線圖形比較高,必須把行高加大,讓上一行文字底部與下一行文字頂部之間有足夠空間,例如 p { line-height: 1.5; },否則圖案會壓到隔行的字。
第三步:關掉預設底線。a { text-decoration: none; }
第四步:掛上背景圖。假設圖檔名為 underline.gif,寫成 a { background-image: url(underline.gif); }
第五步:只往水平方向重複。若允許垂直重複,圖案會鋪滿整個元素並跑到文字背後。a { background-repeat: repeat-x; }
第六步:把圖釘在底部。用 background-position 讓圖形對齊元素底端,這樣不管字級多大,底線都會乖乖待在文字下方。若是箭頭這類有方向性的圖案,還要考慮水平對齊。想放右下角:a { background-position: 100% 100%; }
第七步:留出底部空白。下劃線的位置與字級有關,一般可以先把 padding-bottom 設成等於圖形高度,之後再微調。例如 a { padding-bottom: 4px; }
第八步:禁止換行。因為圖釘在元素底部,一旦連結折成兩行,就只有最後一行下方會出現底線。用 white-space: nowrap 鎖住:a { white-space: nowrap; }
把八步合起來,完整的樣式就是:
a {
text-decoration: none;
background: url(underline.gif) repeat-x 100% 100%;
padding-bottom: 4px;
white-space: nowrap;
}
如果希望底線只在滑鼠停留時出現,把 background 那一行從 a 搬到 a:hover 即可:
a {
text-decoration: none;
padding-bottom: 4px;
white-space: nowrap;
}
a:hover {
background: url(underline.gif) repeat-x 100% 100%;
}
準備兩個圖形:diagonal.gif(波紋線,高 3、寬 9)與 flower.gif(花朵,高 11、寬 15)。把它們和網頁放在同一目錄,然後:
<html>
<head>
<title>自訂下劃線範例</title>
<style type="text/css">
a#example1a {
text-decoration: none;
background: url(diagonal.gif) repeat-x 100% 100%;
white-space: nowrap;
padding-bottom: 2px;
}
a#example1b {
text-decoration: none;
white-space: nowrap;
padding-bottom: 2px;
}
a#example1b:hover {
background: url(diagonal.gif) repeat-x 100% 100%;
}
a#example2a {
text-decoration: none;
background: url(flower.gif) repeat-x 100% 100%;
white-space: nowrap;
padding-bottom: 10px;
}
a#example2b {
text-decoration: none;
white-space: nowrap;
padding-bottom: 10px;
}
a#example2b:hover {
background: url(flower.gif) repeat-x 100% 100%;
}
</style>
</head>
<body>
<p>範例:</p>
<p>
<a href="#" id="example1a">波紋線靜態下劃線</a>,
<a href="#" id="example1b">滑過時才出現的波紋線</a>。
</p>
<p>
<a href="#" id="example2a">花朵靜態下劃線</a>,
<a href="#" id="example2b">滑過時才出現的花朵下劃線</a>。
</p>
</body>
</html>
注意 padding-bottom 要隨圖形高度調整:3px 高的波紋線給 2px 就夠,11px 高的花朵則要給到 10px 才不會壓字。這也是整個技巧唯一需要反覆試的地方。