解决css浏览器兼容问题的几种策略

1.css特殊符号hack
这种方式估计是最多人使用的方式,原理就是利用特殊字符写出只匹配特定浏览器的css,这里给出常用的例子:

IE6

IE7

IE8

IE9

IE10

FF15

Chrome22

Opera12

Safari5.1.7

color:red\9;

Y

Y

Y

Y

Y

color:red\0;

Y

Y

Y

Y

*color:red;

Y

Y

+color:red;

Y

Y

_color:red;

Y

-color:red;

Y


2.条件注释
利用IE特有的条件注释针对个版本IE编写特殊的css
<!--[if lt IE 9]>Less Than IE9<![endif]-->
<!--[if lte IE 9]>Less Than or Equal IE9<![endif]-->
<!--[if IE]>IE only<![endif]-->
<!--[if IE 6]>IE6 only<![endif]-->
<!--[if IE 7]>IE7 only<![endif]-->
<!--[if gt IE 6]> Greater Than IE6<![endif]-->
<!--[if gte IE 6]> Greater Than or Equal IE6<![endif]-->
...

3. CSS 选择器
利用只有特定浏览器才能识别的css选择器,如:

/* IE6 and below */
* html .demo { color: red }
/* IE7 */
*:first-child+html .demo{ color: blue }
/* IE7 */
*+html .demo{ color: blue }
/* Everything but IE6-8 */
:root *> .demo{ color: #000 }

/* Opera、IE7 */
noindex:-o-prefocus, .demo{
color:blue;
}

/* safari5.1.7、chrome22 */
@media screen and (-webkit-min-device-pixel-ratio:0){
.demo { color: blue;}
}
/* FF15 */
@-moz-document url-prefix(){
.demo { color: blue;}
}

4.patch方式
这种方式是根据不同浏览器在页面上追加不同的css补丁文件,这样,补丁中的css就会覆盖通用的css部分,一般会使用条件注释语句或者服务器判断浏览器类型。

5.设置浏览器选择器
这种方法也需要在页面上检查浏览器版本(可以服务器分析、js分析或者其他方式),不过,是直接在body或者其他合适的标签上增加class,如<body class="ie7">,这样,css可以写成:
/* for all */
.demo{ color: blue }
/* ie7 */
.ie7 .demo{ color: red}

总结:
CSS特殊符号 Hack应该是最常用的方式, 使用简单方便,但是通不过 W3C 验证,而且有一定隐患;条件注释的方式局限性很明显,只能针对ie,一般会结合其他方式做;css选择器的方式由于笔者没有在项目中使用过,在此只是简要介绍,不过,它的问题是规则复杂,不容易记住,而且不够灵活;patch和设置浏览器选择器的方式由于可以使用服务器或者js判断浏览器,因此可以获得精确的浏览器类型、版本和浏览器壳(遨游、搜狗之类),功能应该是最强大也最灵活的,而且可读性强,使用简便,又能通过w3c,是比较理想的方式,而相对而言,patch方式需要将一处的css规则写在不同的文件里(通用文件及patch文件),代码分散,不利于维护,因此,笔者较为推荐设置浏览器选择器的方式。
当然,每个团队的情况不一样,适合自己的,才是最好的。


附录 网上的css兼容一览表