用背景圖做按鈕外觀、同時保留文字內容,最經典的做法就是 text-indent 把文字推離視線。這個技巧本身很簡單,但在 IE 下會失效,需要額外補強。
先看基本結構與樣式:
<input type="submit" value="Submit" id="btn" />
#btn {
width: 114px;
height: 37px;
border: none;
background: transparent url(images/submit_btn.gif) no-repeat center;
overflow: hidden;
text-indent: -999px;
}
這段代碼在現代瀏覽器中完美運作,但 IE 完全不理會 text-indent: -999px,文字照樣顯示在按鈕上。
為讓各瀏覽器呈現一致,通常需要在原基礎上補上字級、行高與 display:
#btn {
width: 114px;
height: 37px;
border: none;
background: transparent url(images/submit_btn.gif) no-repeat center;
overflow: hidden;
text-indent: -999px;
font-size: 0;
line-height: 0;
display: block;
}
為什麼是這三行?
font-size: 0——把字級歸零後,IE7 不再顯示文字,達到預期效果。但 IE6 會留下一條與前景色同色的細線。
line-height: 0——正好用來收拾 IE6 那條線。行高歸零後,文字沒有可佔用的垂直空間,線條隨之消失。
display: block——讓 button 以塊級元素呈現,寬高設定才會穩定生效。
有些情況下,設定完畢後按鈕上仍會殘留一個小點。這時可以再加上文字顏色與對齊:
#btn {
width: 114px;
height: 37px;
border: none;
background: transparent url(images/submit_btn.gif) no-repeat center;
overflow: hidden;
text-indent: -999px;
font-size: 0;
line-height: 0;
display: block;
color: #fff;
text-align: right;
}
這裡有個小技巧要特別注意:color 要選與背景相近的顏色,讓人肉眼看不出來。實務上我通常把文字推到左側或右側,再挑最接近的背景色。以本例而言,選擇白色即可。
整體來看,這套做法的核心思想是「視覺隱藏而非結構移除」——文字仍在 DOM 中,螢幕閱讀器與搜尋引擎都能讀到,同時視覺上完全由背景圖接管。