用 DIV+CSS 做版面時,最大的痛點不是語法,而是同一份程式碼在不同瀏覽器下跑出不同結果。以下是兩套分流機制與幾組可直接複用的組合。
自從 IE7 開始支援 !important 之後,這招就只剩「對付 IE6」一個用途了。寫法上有個關鍵:該宣告必須放在前面。
#example {
width: 100px !important; /* IE7 + Firefox */
width: 200px; /* IE6 */
}
先把符號記牢:
所有瀏覽器通用:height: 100px;
IE6 專用:_height: 100px;
IE7 專用:*+height: 100px;
IE6、IE7 共用:*height: 100px;
IE7、Firefox 共用:height: 100px !important;
寫法示例:
#example { height: 100px; } /* Firefox */
* html #example { height: 200px; } /* IE6 */
* + html #example { height: 300px; } /* IE7 */
#example {
height: 100px; /* Firefox */
_height: 200px; /* IE6 */
*+height: 300px; /* IE7 */
}
或者另一種寫法:
#example {
height: 100px; /* Firefox */
*height: 300px; /* IE7 */
_height: 200px; /* IE6 */
}
#example {
height: 100px; /* Firefox */
*height: 200px; /* IE6 + IE7 */
}
#example {
height: 100px; /* IE6 + Firefox */
*+height: 200px; /* IE7 */
}
#example {
height: 100px !important; /* Firefox + IE7 */
height: 200px; /* IE6 */
}
這是使用 hack 時最容易犯、也最難察覺的錯誤。瀏覽器在解析樣式時,遇到重複的屬性會「後者覆蓋前者」,就像變數賦值一樣。所以規則必須由「通用」排到「專用」。
以三瀏覽器各自不同的那段為例,逐行解讀:
第一行 height: 100px;——三家都讀到,此時都是 100px。
第二行 *height: 300px;——Firefox 不認這個寫法,跳過,仍是 100px;IE6 與 IE7 認得,把值覆蓋成 300px。
第三行 _height: 200px;——只有 IE6 認得,於是再覆蓋一次,最終顯示 200px。
結果:Firefox 100px、IE7 300px、IE6 200px,三家各取所需。順序一換,覆蓋關係就亂了。
*+html 要對 IE7 生效,文件頂部必須有完整的 DOCTYPE 宣告:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd">
少了它,IE7 會跑進 quirks mode,*+html 選擇器隨之失效,整組 hack 就白寫了。
以上全部屬於歷史知識。新專案請用特性偵測取代瀏覽器 hack:以 Modernizr 之類的工具偵測能力,在 html 元素上掛 .flexbox 或 .no-flexbox 這類 class,再針對 class 寫樣式。這樣做有兩個好處——程式碼能自我說明意圖,而且新瀏覽器問世時不必修改任何判斷條件。