按鈕文字長度不一,如果直接給固定寬度的圖片當背景,文字一多就會溢出。解法是把一張「足夠寬的圓角圖」拆成左右兩端:左端固定不動,右端靠右對齊,中間則讓背景自然延伸。這樣按鈕寬度就能隨文字伸縮,兩端的圓角卻不會變形。
用 <a> 包 <span> 兩層元素:外層 a 的背景定位在 0 0(左端),內層 span 的背景定位在 top right(右端)。內層再用負的 margin 把自己往左拉,讓兩張圖的圓角部分重疊對齊。滑過時只要換成背景圖的另一組 y 座標即可。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh-Hant">
<head>
<title>自適應寬度按鈕</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
* { padding: 0; margin: 0; }
body { font-size: 12px; }
h2 { margin: 50px; }
a {
text-decoration: none;
background: url(https://www.w3css.com/1.jpg) 0 0;
float: left;
color: #fff;
margin: 0 60px 0 0;
cursor: pointer;
}
a span {
position: relative;
background: url(https://www.w3css.com/1.jpg) top right;
line-height: 25px;
margin: 0 -30px 0 30px;
padding-right: 30px;
float: left;
}
a:hover {
background: url(https://www.w3css.com/1.jpg) left -25px;
height: 25px;
float: left;
margin: 0 60px 0 0;
}
a:hover span {
background: url(https://www.w3css.com/1.jpg) right -25px;
line-height: 25px;
margin: 0 -30px 0 30px;
padding-right: 30px;
float: left;
color: #fff;
}
</style>
</head>
<body>
<h2>自適應寬度按鈕</h2>
<a href="#" title="nogo"><span>自適應</span></a>
<a href="#" title="nogo"><span>自適應寬度</span></a>
<a href="#" title="nogo"><span>自適應寬度,對吧!</span></a>
</body>
</html>
line-height: 25px:決定按鈕高度,同時讓文字垂直居中。
margin: 0 -30px 0 30px:左邊推開 30px 讓出左端圓角的空間,右邊用 −30px 把多餘的寬度收回來,避免兩端圖片之間出現縫隙。這兩個 30 必須與 padding-right: 30px 對應,也就是「圓角區塊的實際半徑」。
background-position 的 −25px:把同一張圖往上推一個按鈕高度,露出預備好的 hover 態圖。這就是所謂的 CSS Sprite——把多種狀態拼在一張圖上,靠位移切換,只發一次請求。
背景圖的寬度必須大於按鈕可能達到的最大寬度,否則文字變長時右側圓角會消失。做法是把圖片做寬一點(例如 400px),左端放圓角、右端放圓角,中間填純色,這樣在 30px 到 370px 之間都能正常顯示。
另外,a 與 span 都設了 float,父層記得清除浮動,否則後續內容會黏上來。這個技巧在 CSS3 的 border-radius 普及後已被取代,但它示範的「多層元素各承擔一部分背景」思路,在做出斜面、陰影、多重邊框等效果時依然通用。