圓角區塊讓版面看起來柔和舒服,在 border-radius 普及之前,這卻是個頗費工的活儿。以下整理三種曾經主流的做法,順便說明各自的限制——理解它們,也能幫你判斷該不該回頭用圖片方案。
網路上流傳最廣的一種,靠四層遞移的 margin 模擬出圓角的階梯:
<html>
<head>
<title>CSS 實現 DIV 圓角的三種方法</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<style type="text/css">
<!--
body { color: #fff; }
div.RoundedCorner { background: black; }
b.R_top, b.R_bottom { display: block; background: #FFFFFF; }
b.R_top b, b.R_bottom b {
display: block;
height: 1px;
overflow: hidden;
background: black;
}
b.R_1 { margin: 0 5px; }
b.R_2 { margin: 0 3px; }
b.R_3 { margin: 0 2px; }
b.R_top b.R_4, b.R_bottom b.R_4 { margin: 0 1px; height: 2px; }
-->
</style>
</head>
<body>
<div class="RoundedCorner">
<b class="R_top">
<b class="R_1"></b>
<b class="R_2"></b>
<b class="R_3"></b>
<b class="R_4"></b>
</b>
<p>圓角 DIV 內容</p>
<b class="R_bottom">
<b class="R_4"></b>
<b class="R_3"></b>
<b class="R_2"></b>
<b class="R_1"></b>
</b>
</div>
</body>
</html>
取捨:不需要任何圖片,靈活性也不差;但每次使用都要在內容前後塞進一大段標籤,而且圓角半徑寫死在 margin 裡,想調整就得重算每一層。
事先在 Photoshop 或 Fireworks 畫好一張帶圓角的背景圖,直接掛上去:
div {
background: url(圖片url) no-repeat;
}
取捨:呼叫方式最簡單,一行搞定;但靈活性最差。容器要改寬度或高度,就得重做一張背景圖。適合尺寸固定的裝飾性區塊。
同樣是背景圖,但拆成三個 div:左端放圓角背景的最左側、中間用 1px 寬的圖横向平鋪填滿、右端放最右側。
div_l {
float: left;
background: url(圓角背景的最左邊部分圖片url) no-repeat;
/* 自行設定高度與寬度 */
}
div_m {
float: left;
background: url(1像素背景填充圖片url) repeat-x;
/* 自行設定高度與寬度,背景橫向重複 */
}
div_r {
float: left;
background: url(圓角背景的最右邊部分圖片url) no-repeat;
/* 自行設定高度與寬度 */
}
<div class="div_l"></div>
<div class="div_m">DIV 內容 DIV 內容</div>
<div class="div_r"></div>
取捨:步驟最多,需要三張圖與三個容器;但換來了任意寬度的支援,是當年最實用的折衷方案。
今天這三招都已被 border-radius 一句話取代。但它們示範的「用有限資源模擬曲線」的思路,在做複合形狀或特殊邊角時偶爾還派得上用場。