只要做過網頁切版,大概都躲不過同一個命題:同一份 CSS,在 IE6、IE7 看起來正常,換到 Firefox 卻走了樣。本文整理兩條最常被使用的解法,並附上各瀏覽器對選擇器與 Hack 的支援對照,方便你在實戰中快速定位。
核心思路是把同一個屬性重複宣告,靠前綴符號讓不同瀏覽器各自讀懂「看得懂的那一行」。寫法如下:
#someNode {
position: fixed;
#position: fixed;
_position: fixed;
}
第一行給 Firefox 與其他標準瀏覽器;第二行給 IE7;第三行給 IE6 與更舊的版本。實用價值之一是讓 IE6「假裝」支援 position:fixed。搭配 IE6 的 expression,甚至不必額外載入 JavaScript:
#ff-r {
position: fixed;
_position: absolute;
right: 15px;
top: 15px;
_top: expression(eval(document.compatMode &&
document.compatMode == 'CSS1Compat') ?
documentElement.scrollTop + 15 :
document.body.scrollTop +
(document.body.clientHeight - this.clientHeight)));
}
另一條路是為不同瀏覽器準備各自獨立的樣式表,在讀取頁面時依瀏覽器種類與版本號載入對應檔案。判斷方式又分兩支:用 JavaScript 在前端嗅探,或直接在伺服器端依 User-Agent 輸出對應樣式。前端做法靈活但依賴腳本執行;後端做法穩定,卻需要維護多份樣式。
在正常寫法 selector{property:value;} 之上,實務上常針對同一元素疊加 Hack,換取跨瀏覽器的一致呈現。
selector{+property:value;}:屬性名前加「+」,僅 IE 系列可辨識。selector{*property:value;}:屬性名前加「*」,僅 IE 系列可辨識。selector{_property:value;}:屬性名前加底線「_」,僅 IE6 及更舊版本可辨識,IE7 不認。*html selector{property:value;}:僅 IE6 及更舊版本可辨識。html/**/>body selector{property:value;}:僅 IE6 及更舊版本可辨識。selector{property/**/:value;}:在屬性名與冒號之間插入註解,可屏蔽 IE6。selector/**/{property/**/:value;}:屏蔽 IE5 與 IE6,但不影響 IE5.5。select/**/{property:value;}:屏蔽 IE5。*+html selector{property:value!important;}:僅 IE7 可辨識。*:lang(lang) selector{property:value!important;}:偽類 lang 加上 !important,當時只有 Firefox 吃這一套。
selector:empty{property:value!important;}:偽類 empty 搭配 !important,當時只有 Safari 吃這一套。
@media all and (min-width:0px){selector{property:value;}}:利用特殊繼承寫法,當時只有 Opera 吃這一套。
實務上最常動用 Hack 的地方,莫過於 CSS 盒模型與清除浮動。
IE5.x 對盒模型的解析有嚴重錯誤,可針對它寫:
selector {
width: IE5X的寬度;
voice-family: "\"}\"";
voice-family: inherit;
width: 正確的寬度;
}
清除浮動則常用偽元素收尾:
selector:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
兩條路各有代價:Hack 讓樣式變髒、可讀性下降;分流樣式表則增加維護成本。選擇哪一條,取決於你的專案需要支援到多舊的版本。