跨瀏覽器的樣式差異是前端開發的例行工作。要精準地為不同瀏覽器指定不同樣式,先要記住各瀏覽器對特定語法的解析能力。
區別 IE6 與 Firefox:
background:orange; /* Firefox */ *background:blue; /* IE6 */
區別 IE6 與 IE7:
background:green !important; /* IE7 */ background:blue; /* IE6 */
區別 IE7 與 Firefox:
background:orange; /* Firefox */ *background:green; /* IE7 */
同時區別三者:
background:orange; /* Firefox */ *background:green !important; /* IE7 */ *background:blue; /* IE6 */
關鍵在於各瀏覽器對兩個語法標記的支援程度:
* 前綴:IE6 與 IE7 都吃,標準瀏覽器(如 Firefox)不認。!important:IE7 與 Firefox 都吃,IE6 雖能解析但不會當成高優先級。整理成表:
IE6 IE7 Firefox * 前綴 ✓ ✓ ✗ !important ✗ ✓ ✓
底線 _ 只有 IE6 支援,IE7 與 Firefox 都不認。於是可以寫成:
background:orange; /* Firefox */ *background:green; /* IE7 */ _background:blue; /* IE6 */
不論用哪一種寫法,順序必須是:Firefox 的規則寫在最前面,IE7 在中間,IE6 放在最後。因為後者會覆蓋前者,順序錯了整組 hack 就失效。
.p_redirect{
background-color:#f5f5f5;
border:1px solid #A3C2E0;
margin-right:1px;
font-size:12px !important;
font-size:13px;
}
這裡的目的是讓 Firefox 顯示 12px、IE 顯示 13px。原理是:IE 不認 !important 的優先效果,因此採用最後設定的 13px;Firefox 認得 !important,於是採用 12px。
這類 hack 屬於舊時代的產物,每多一層 hack,樣式表的可讀性就下降一階。若專案仍需支援舊版 IE,建議把 hack 集中寫在同一個區塊並加上註解說明,或者改用條件式註解載入獨立樣式表,會比散落在各處好維護得多。