剛開始做網頁的人,常被這幾個問題困住:連結的底線怎麼去掉?滑鼠移上去怎麼變色?能不能順便變字級?點過的連結換個顏色行不行?
這些用 CSS 都能輕鬆做到,而且最大的好處是——設定一次,全站生效,不必一個一個 <a> 去改屬性。以下從最基礎的四狀態講起。
在 <head> 與 </head> 之間加上:
<style type="text/css">
<!--
a:link { text-decoration: none } /* 正常、尚未造訪過 */
a:active { text-decoration: none } /* 點擊的那一瞬間 */
a:visited { text-decoration: none } /* 已經造訪過 */
a:hover { text-decoration: none } /* 游標停放其上 */
-->
</style>
很多人以為連結只有三個狀態,因為多數所見即所得軟體的介面裡也只列了 link、active、visited。hover 常被漏掉,但它其實非常重要——它是唯一能回應「游標接近」的狀態,而且還能額外指定背景色(background: #ccffcc)。請記住:連結有四個狀態可以設定。
text-decoration 是文字裝飾屬性。none 不加裝飾;underline 加底線;overline 在字的上方加線;line-through 是刪除線;還有一個 blink 是閃爍,但只有 Netscape 看得見,實務上不必考慮。
加刪除線:B { text-decoration: line-through }
全部字母大寫:B { text-transform: uppercase }(舊 IE 對此支援不佳)
同時具備大寫、顏色與刪除線:
b { text-decoration: line-through; text-transform: uppercase; color: #66FFFF }
另外,lowercase 讓所有字母變小寫,capitalize 讓每個單字的首字母大寫。
<style type="text/css">
<!--
a:link { text-decoration: none; color: green } /* 正常:綠 */
a:active { text-decoration: none; color: yellow } /* 點擊瞬間:黃 */
a:visited { text-decoration: none; color: red } /* 已造訪:紅 */
-->
</style>
寫到這裡,三種狀態各自有了顏色,但游標移上去不會有任何反應。要補上這塊,一樣得靠 hover:
a:hover { text-decoration: none; color: yellow; background: white }
這行的意思是:游標移入時維持無底線,文字轉黃,並在文字下方墊一塊白色底。
<style type="text/css">
<!--
a:link { text-decoration: none; color: blue; font-size: 9pt }
a:active { text-decoration: underline; color: yellow; font-size: 10pt }
a:visited { text-decoration: none; color: red; font-size: 10.5pt }
a:hover { text-decoration: underline; color: green; font-size: 11pt; background: white }
-->
</style>
逐條翻譯成白話:
第一,四種狀態的撰寫順序建議維持 link → visited → hover → active。這是因為 CSS 的層疊規則會讓後寫的同權重規則覆蓋先寫的;若把 visited 寫在 hover 之後,已造訪過的連結移入時就不會變色了。
第二,字級在 hover 時放大会讓該元素佔用的寬度改變,可能把隔壁的元素推開。若版面很緊,改用 font-weight 或 letter-spacing 這類不影響盒模型的方式,視覺效果相似卻不會撐動版面。