纯CSS实现圆角、阴影、渐变等
UI要求越来越高,界面越做越华丽,给我们开发人员带来的就是使用大量的背景图片,下面介绍一些通过css(不使用图片或少使用图片)来实现一些很常见的效果,
圆角效果
圆角用的越来越多,因为圆角确实好看,效果如下:

要实现上面的圆角,一般切图是左,右(或上下)各切1个图片做背景,但这样做只适合固定宽度或高度的box,而且如果box背景不一样,图片需要另外切。
现在很多浏览器都支持圆角的css,css3也支持,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | .b_box{ text-align:center; width:200px; line-height:60px; border:1px solid #C0C0C0; background-color:#DBEAFF; /*firefox*/ -moz-border-radius: 5px; /*css3*/ border-radius: 5px; /*webkit*/ } |
效果:

但IE9以下的版本都不支持圆角,所以上面的效果在ie9以下显示还是直角的.
目前我们针对ie9以下的浏览器使用下面的方法实现,切1个透明的圆形图片(这个图片要求圆角内测是透明的,而外侧是不透明的),用绝对定位来显示4个圆角,这样做的好处是只使用1个图片,即可以实现任何大小,任何背景颜色的box圆角,但缺点就是需要多余的HTML代码,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <style type="text/css"> .b_box_ie{ text-align:center; width:200px; line-height:60px; background-color:#DBEAFF; position:relative; } .b_r{width:3px;height:3px;font-size:0;background:url(圆角) no-repeat;position:absolute;} .r_1{top:0;left:0;} .r_2{background-position:-3px 0;top:0;right:0;} .r_3{background-position:0 -3px;left:0;bottom:0;} .r_4{background-position:-3px -3px;bottom:0;right:0;}<style> <div class="b_box_ie"> CSS 小技巧 <div class="b_r r_1"></div> <div class="b_r r_2"></div> <div class="b_r r_3"></div> <div class="b_r r_4"></div> </div> |
因我切的图片是gif,而不是png,所以效果不太好看(不像真真的圆角)。效果如下:

而crazyfrom网站的圆角就是用这种方法实现的,但图片是png的!
阴影效果
如果要实现这样的效果,使用图片,切图都很麻烦,让我们看看css如何实现吧,代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | .b_shadow{ height:60px; line-height:60px; width:200px; border:1px solid #C0C0C0; background-color:#DBEAFF; -moz-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5); /*IE6,IE7语法*/ filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=5, OffY=5, Color='gray'); /*IE8语法,可恶的IE,不同的版本还要写的不一样*/ -ms-filter:"progid:DXImageTransform.Microsoft.dropshadow(OffX=5, OffY=5, Color='gray')" } |
结合圆角,实现效果如下:

注:针对IE的filter,再测试过程中发现必须加height和background-color,如果不设置height,则无阴影效果,如果不设置背景色,则阴影效果不是作用在box 上,而是在文字上,原因不是很清楚,有兴趣的同学可以自己测下。
渐变效果:
这个效果也应该也是用的最多的
1 2 3 4 5 6 7 8 | .gradients{ text-align:center; width:200px; line-height:60px; background-image: -moz-linear-gradient(top, #BDD738, #7E9516); background-image: -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#BDD738,endColorstr=#7E9516)"; } |
注:针对IE的filter,再测试过程中发现必须加height和background-color,如果不设置height,则无阴影效果,如果不设置背景色,则阴影效果不是作用在box上,而是在文字上,原因不是很清楚,有兴趣的大虾可以自己测下。
按钮发光效果:
该效果在IE6下看不出来,是因为没有对PNG进行处理,代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <style> .b_btn{ padding:5px 10px; color: #fff; background:url(图片1) repeat-x; text-decoration: none; font-weight: bold; } .b_btn:hover{ background:url(鼠标经过图片2) repeat-x; }</style> <a class="b_btn" href="javascript:void(0);" style="background-color:#2daebf;">按钮1</a> <a class="b_btn" href="javascript:void(0);" style="background-color:#e33100;">按钮2</a> |

