我們時常會遇到圓角的需求。起初我也很天真地以為,靠 CSS3 新特性並對瀏覽器分級支援就是最佳解法,但現實往往不如理想。
經典的解法大致長這樣:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>傳統方案及bug</title>
<style>
body{margin:100px;background-color:red;}
div, p, b{margin:0;padding:0;}
b{display:block;}
.rc{display:inline-block;#display:inline;#zoom:1;}
.rc1, .rc2, .rc .bd{border-style:solid;border-color:black;background-color:yellow;}
.rc1, .rc2{height:1px;overflow:hidden;}
.rc2, .rc .bd{border-width:0 1px;}
.rc1{margin:0 2px;height:0;border-width:1px 0 0;}
.rc2{margin:0 1px;}
.rc .bd{padding:0 6px;line-height:1.5;}
</style>
</head>
<body>
<div class="rc">
<b class="top"><b class="rc1"></b><b class="rc2"></b></b>
<div class="bd">
<p>FML!!!</p>
</div>
<b class="bottom"><b class="rc2"></b><b class="rc1"></b></b>
</div>
</body>
</html>
讓 .rc 使用 float:left 或 display:inline-block 或許能滿足需求,但 IE6 與 IE7 會出問題:IE6 中它依然顯示為 display:block,IE7 中 top 和 bottom 則縮成一團不肯展開;而在 rc1/rc2/rc3 中插入文字
<b class="rc1">XXX</b>
又只會擴展到文字 XXX 的寬度,無法與 bd 對齊。如果你能搞定這個 bug,歡迎留言告訴我。
試了幾種方法都行不通,也搜不到這個 bug,這時我想起了 Google 系列產品那種 1px 圓角按鈕:
這是前 Google 視覺設計師 Doug Bowman 的功勞,他後來轉戰 Twitter,並為此寫過一篇博文《Recreating the button》。不過 demo 終究只是 demo,產品中真正使用的,是某對天才工程師夫婦的神作,他們有足夠的時間把這件事做到位:
The magical inline-block solved everything, except in IE. That's where the genius of Google engineers came in. They knew how to get tricks working in all browsers, and this technique interested a couple of them enough that they dedicated the time to make it work.
打開 Gmail,用 firebug 研究一番後,我心裡暗罵一句:天才就是天才!於是我寫了個簡單的 demo(為了方便演示,這裡採用了盒子諧的顏色):
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>自適應圓角</title>
<style>
body{margin:100px;background-color:red;}
div, p{margin:0;padding:0;}
.div1, .div2, .div3{display:inline-block;#display:inline;#zoom:1;position:relative;border-style:solid;border-color:black;}
.div1{border-width:1px;}
.div2, .div3{#left:-2px;border-width:0 1px;background-color:yellow;}
.div2{margin:0 -2px;}
.div3{margin:1px -2px;padding:0 6px;line-height:1.5;}
.pointer1, .pointer2{position:absolute;top:7px;width:0;height:0;overflow:hidden;border-top:6px transparent dotted;border-bottom:6px transparent dotted;}
.pointer1{left:-9px;border-right:6px black solid;}
.pointer2{left:-8px;border-right:6px yellow solid;}
</style>
</head>
<body>
<div class="div1">
<div class="div2">
<div class="div3">
<p>FML!!!</p>
</div>
</div>
<div class="pointer1"></div>
<div class="pointer2"></div>
</div>
</body>
</html>
效果如下:
不僅滿足了所有需求,程式碼量與結構嵌套也很少。
由此可見,IE6 與 IE7 bug 眾多的特點在這個例子中表現得淋漓盡致。
阮一峰老師也寫過一篇《製作 Gmail 式按鈕》,搭配強大的 jQuery 來實現按鈕的各種狀態,最後的總結也很精彩,稍作修改如下:
雖然這種按鈕(圓角)的視覺效果比較理想,有許多設計上的優點,但局限性也很大。一方面,它需要大量冗餘程式碼,與語義化的原則相違背……
真正完美的方案,還是善用瀏覽器自身特性、對不同瀏覽器分級支援、漸進增強(例如 IE 下顯示直角,對 CSS3 支援較好的瀏覽器顯示圓角),這才是開發效率、可維護性、語義與效能之間的最佳平衡。