網頁設計最麻煩的環節之一,就是跨瀏覽器的相容性。IE 6、IE 7、Firefox 2、Opera 9 對 CSS 的解讀不盡相同,同一份樣式在不同瀏覽器下呈現不同面貌。最常被使用的解法就是 CSS Hack——用特定的語法寫法,讓不同瀏覽器各自讀到該讀的規則。
最廣泛使用的是 !important。IE7 能正確理解它,IE6 則不能,於是只要在宣告後加上 !important,就能讓非 IE6 的瀏覽器採用這個值。
* html select { ... } /* 僅 IE6 及更早版本讀取 */
*+html select { ... } /* 僅 IE7 讀取 */
*+html select { ... !important; }
/* 1. IE7 與 IE5.0 可識別 */
*+html select { ... }
/* 2. 僅 IE7 可識別 */
*+html select { ... !important; }
/* 3. IE6 及 IE6 以下可識別(IE5.x 同樣適用) */
* html select { ... }
/* 4. 同上,另一種寫法 */
html/**/ > body select { ... }
/* 5. 僅 IE6 不識別(屏蔽 IE6) */
select { display /*屏蔽IE6*/ : none; }
/* 6. IE6 與 IE5 不識別(不屏蔽 IE5.5) */
select/**/ { display /*IE6,IE5不識別*/ : none; }
/* 7. 僅 IE5 不識別 */
select/*IE5不識別*/ { ... }
/* 8. 盒模型修正 */
select {
width: IE5.x的寬度;
voice-family: "\"}\"";
voice-family: inherit;
width: 正確的寬度;
}
/* 9. 僅 Opera 識別 */
@media all and (min-width: 0px) {
select { ... }
}
值得留意的是,很多文章把 * html 說成「IE6 專用 Hack」,實際上 IE5.x 也讀得懂它。
若希望相容性相關的程式碼不要混進主樣式表,可以改用過濾器,在特定條件下才載入補丁樣式:
/* IE5.x 專用 */
@media tty {
i{content:"\"/*\" ""*/";}} @import 'ie5win.css'; /*";" */
}/* */
/* IE5/Mac 專用 */
/*\*/ @import "ie5mac.css"; /**/
IE 支援的一組條件語法,是最乾淨也最可控的相容方案:
<!--[if IE]> 所有 IE 版本 <![endif]--> <!--[if IE 5.0]> 僅 IE 5.0 <![endif]--> <!--[if gt IE 5.0]> IE 5.0 以上 <![endif]--> <!--[if lt IE 6]> IE 6 以下 <![endif]--> <!--[if gte IE 6]> IE 6 以上 <![endif]--> <!--[if lte IE 7]> IE 7 以下 <![endif]-->
*,標準瀏覽器(如 Firefox)不認得。*,但不認得 !important。*,但認得 !important。於是 *width:10px; !important width:20px; 這種寫法,在 IE6 下寬度是 10px,在 IE7 下則是 20px。
.e { background-color: #FF0000; } /* Firefox / Opera */
html* .e { background-color: #FF00FF; } /* Safari / IE7 / Opera */
*+html .e {
background-color: #000000; /* Opera */
*background-color: #0000FF; /* IE7 */
}
* html .e { background-color: #00FFFF; } /* IE6 */
第一,IE7 對樣式的解讀與 DTD 有關。缺少 DTD 時,IE7 會進入相容模式,連 IE6 的 Hack 都照讀——所以「忘了寫 DTD」往往才是問題的根源,而不是 Hack 寫錯。
第二,Hack 依賴的是 bug,本質上是借貸來的相容性。能用標準語法避開的,就不要動用 Hack;必須使用時,把它們集中到獨立檔案或加上清楚的註解,日後要清理才不會無所從頭。