有时候我们不得不面对圆角,也很傻很天真的认为利用 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;} /* float 效果相同 .rc{float:left;} */ .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 或许能满足需求,不过 IE 6&7 出现 bug:IE6中依然显示为dispaly:block,而IE7中top 和 bottom缩成一坨,不肯扩展开来,而在 rc1/rc2/rc3 中插入文字
<b class="rc1">XXX</b>
则只能扩展到文字XXX的宽度,无法与 bd 对齐!
如果你能搞定,麻烦留言告诉我一下 :)
试了几个方法均不通,也搜索不到这个 bug,这时想到了 Google 系产品的 1px 圆角按钮:
这是前 Google 视觉设计师 Doug Bowman 的功劳,后转会到Twitter(AD一下:@ytzong),Doug Bowman 为此写过一篇博文《Recreating the button》 demo在此。不过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>
效果如下:
不仅满足了需求,代码量及结构嵌套也很少。
可以看出:IE 6&7 bug 众多的特点在此例中表现的淋漓尽致!
阮一峰老师也写过一篇《制作Gmail式按钮》,配合强大的 jquery 来实现按钮各种状态,最后的总结也很精彩,修改一下下:
虽然这种按钮(圆角)的视觉效果比较理想,有很多设计上的优点,但是局限性也很大。一方面,它需要大量的冗余代码,与语义网的原则相违背…
完美方案还是利用浏览器的自身特性提供对不同的浏览器分级支持,渐进增强(比如 IE 下显示为直角,对CSS 3支持较好的浏览器显示为圆角),这才是开发效率、可维护性、语义、性能的最佳平衡。