在 border-radius 普及之前,圓角是靠四張角圖加絕對定位拼出來的。以下是一套完整可用的寫法。
.border {
background: #ffecf9;
border: 1px solid #ffd3ec;
width: 500px;
position: relative;
}
.lt {
background: url(../images/border_lt.gif) no-repeat;
left: 0; top: 0;
position: absolute;
width: 7px; height: 7px;
}
.rt {
background: url(../images/border_rt.gif) no-repeat;
right: 0; top: 0;
position: absolute;
width: 7px; height: 7px;
}
.lb {
background: url(../images/border_lb.gif) no-repeat;
left: 0; bottom: 0;
position: absolute;
width: 7px; height: 7px;
}
.rb {
background: url(../images/border_rb.gif) no-repeat;
right: 0; bottom: 0;
position: absolute;
width: 7px; height: 7px;
}
.content {}
<div class="border"> <div class="lt"></div> <div class="rt"></div> <div class="lb"></div> <div class="rb"></div> <div class="content">This is content.</div> </div>
其中 border_lt.gif 等四張圖就是四個角的圓角圖,需要自行切齊,尺寸視圓角大小而定;位置則由 left、top、right、bottom 絕對控制。
一、相對定位的 .border 層必須至少定義寬度或高度其中一項。若不定義,Firefox 可以正常顯示,但 IE 會出現各種問題——因為絕對定位的子元素無法撐開父元素,父元素高度會塌陷為 0。
二、IE 下的邊緣位置可能有細微差異。針對 IE 另外指定即可:
.lb {
background: url(../images/border_lb.gif) no-repeat;
left: -1px !important;
left: -5px;
bottom: -1px !important;
bottom: -5px;
}
這裡用了 CSS hack:同一個屬性寫兩次,!important 那行給標準瀏覽器,後一行給 IE6 讀取。實際偏移量需依情況微調。
除了需要四個額外的標籤與四張圖檔(等於四個 HTTP 請求),還有幾個痛點:圓角一大就得重切圖;帶背景色的容器無法真正填滿圓角內的區域;要改圓角風格得回到圖片編輯軟體。
現在只需要一行:
.border {
background: #ffecf9;
border: 1px solid #ffd3ec;
width: 500px;
border-radius: 7px;
}
不需要額外表單元素、不需要圖檔、可任意調整弧度,且支援所有現代瀏覽器。若圓角內還有圖片或需要裁切,加上 overflow: hidden 即可。
保留這份寫法作為理解絕對定位與 CSS hack 的教材仍有價值,但在任何新專案中,它都應該被 border-radius 取代。