CSS 給了設計者非常靈活的控制手段,但說到下劃線,可選項目卻意外地少。我們平常看到的底線幾乎都是一條筆直的橫線,少了點靈氣。不過只要稍作改造,還是可以做出別出心裁的底線,讓頁面更耐看。
先看一個例子:自定義的下劃線。除了讓網站風格與眾不同,它還能替不同類型的文字給出不同的視覺提示,起到標記或強調的作用。
第一步是準備作為底線的圖片,現成的或自己畫都可以。要留意的是,這張圖必須適合在水平方向重複,最好存成透明的 GIF,這樣背景才不會被遮住。
另外,如果底線圖的高度(粗細)佔了比較多像素,就應該把行距撐開一些,避免和下一行黏在一起:
p { line-height: 1.5; }
接著先把瀏覽器自帶的下劃線拿掉,才有辦法套上自訂版本:
a { text-decoration: none; }
用準備好的圖當作連結元素的背景圖:
a { background-image: url(underline.gif); }
由於文字長度未必等於圖片寬度,需要處理重複的問題,把重複方向限制在 X 軸:
a { background-repeat: repeat-x; }
還有個問題:字級改變時怎麼辦?要讓底線永遠貼在文字下方,用 background-position 把它定位在元素底部即可。若底線是箭頭這類圖案,還得考慮文字邊緣與圖片邊緣的對齊,例如下面這個例子把底線定位在右下角:
a { background-position: 100% 100%; }
這可以靠 padding 來控制。底線圖相對文字基線(baseline)的精確位置會隨字級而變,建議先把 bottom padding 設成與底線圖同高,再慢慢微調。以下把底部內距設為 4px:
a { padding-bottom: 4px; }
因為底線圖被定位在元素底部,所以要確保連結文字不會換行,否則只有最下面那行會出現底線。用 white-space 屬性來阻止換行:
a { white-space: nowrap; }
把上面幾項合併起來,結果是:
a {
text-decoration: none;
background: url(underline.gif) repeat-x 100% 100%;
padding-bottom: 4px;
white-space: nowrap;
}
還記得那種平時沒有底線、滑鼠移上去才浮現的效果嗎?只要把背景圖從 a 移到 :hover 上就好:
a {
text-decoration: none;
padding-bottom: 4px;
white-space: nowrap;
}
a:hover {
background: url(underline.gif) repeat-x 100% 100%;
}
靜態底線
a#example3a {
text-decoration: none;
background: url('20110410213119420.gif') repeat-x 100% 100%;
white-space: nowrap;
padding-bottom: 2px
}
滑鼠移過才浮現
a#example3b {
text-decoration: none;
white-space: nowrap;
padding-bottom: 2px;
}
a#example3b:hover {
background: url('20110413035610859.gif') repeat-x 100% 100%;
}
花朵底線(靜態與動態兩版)
a#example4a {
text-decoration: none;
background: url('20110410213119962.gif') repeat-x 100% 100%;
white-space: nowrap;
padding-bottom: 10px
}
a#example4b {
text-decoration: none;
white-space: nowrap;
padding-bottom: 10px;
}
a#example4b:hover {
background: url('20110410213119962.gif') repeat-x 100% 100%;
}
箭頭底線
a#example1a {
text-decoration: none;
background: url('20110410213119876.gif') repeat-x 100% 100%;
white-space: nowrap;
padding-bottom: 5px
}
箭頭動畫(滑鼠移過時箭頭滾動,此效果僅部分瀏覽器看得到)
a#example2b {
text-decoration: none;
white-space: nowrap;
padding-bottom: 5px;
}
a#example2b:hover {
background: url('20110410213119725.gif') repeat-x 100% 100%;
}
原理就是這幾個屬性的排列組合,剩下的看你怎麼換圖片。搭配不同的 padding 值與圖檔,就能變化出相當多花樣。