以前做網頁,只要考慮 IE6 與 Firefox 的相容性還算輕鬆;後來公司要求提高,Firefox 與 IE6、IE7、IE8 全都要相容,這時就難免會遇到需要單獨 Hack 某個版本的情況。
用條件註釋當然方便,只要加上對應註釋就能解決。但問題是:為了一兩句 CSS 而多開一個文件,或在 header 裡插入一堆註釋,顯然不是勤勞開發者想做的事。於是,我們整理出下面這套依序覆蓋的寫法:
selector {
property: value; /* 所有瀏覽器 */
property: value\9; /* 所有 IE 瀏覽器 */
+property: value; /* IE7 */
_property: value; /* IE6 */
}
依據 CSS 的優先性,上述寫法可分別針對 Firefox、IE8、IE7、IE6 顯示對應的值。關鍵在於書寫順序。來看一個實際例子:
p.IE {
height:60px; text-align:center; line-height:60px;
border:1px dashed #bbb; background:#f7f7f7;
color:blue; /* 所有瀏覽器 */
color:brown\9; /* 所有 IE 瀏覽器 */
+color:red; /* IE7 */
_color:green; /* IE6 */
}
區分 IE6/7 與 FF/IE8:
background:blue; *background:orange;
原理:Firefox 與 IE8 不支援以 * 開頭的寫法,而 IE6/7 支援。
區分 IE6 與 IE7/IE8/FF:
background:green; _background:blue;
原理:只有 IE6 認得底線 _,IE7、IE8 與 Firefox 都不支援。
同時區分 IE6、IE7、IE8、Firefox:
.test {
color:#000; /* Firefox */
color:/*\*/#00f\9; /* IE8 */
*color:#f00; /* IE7 */
_color:#0f0; /* IE6 */
}
如果你更偏好分離式管理,也可以用條件註釋為不同 IE 版本載入各自的樣式檔:
<!--[if IE 6]> <link rel="stylesheet" type="text/css" href="css/IE6style.css" media="screen" /> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="css/IE7style.css" media="screen" /> <![endif]--> <!--[if gte IE 8]> <link rel="stylesheet" type="text/css" href="css/IE8style.css" media="screen" /> <![endif]-->
需要提醒的是,上述 hack 寫法適用於 XHTML 1.0,且必須在 HTML 最前面加上正確的 DOCTYPE 宣告,否則效果會大打折扣。此外,這裡所說的 IE8 指的是真正的 IE8 標準模式,而非其實等同 IE7 的相容模式。