解決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兼容一覽表