裝好 IE8 正式版後,把常用的幾個 CSS hack 歸納一次,希望對做 div + CSS 的人有幫助。本文以 IE6、IE7、IE8、IE9 與 Firefox 為對象。
不同瀏覽器對特殊字元的辨識能力不同。讀完你會發現,Firefox 與 IE8 對下列字元的辨識行為完全相同。
| 字元 | 辨識情況 |
|---|---|
| * | IE6、IE7 能辨識;Firefox 與 IE8 不能 |
| !important | 除 IE6 外,Firefox、IE7、IE8 都能辨識 |
| _ | 只有 IE6 支援 |
| \9 | 所有 IE 版本(IE6、IE7、IE8、IE9)都辨識 |
| \0 | 只對 IE8 有效 |
區分 Firefox(含 IE8)與 IE6/IE7:
background: orange; /* Firefox、IE8 顯示橘黃 */ *background: red; /* IE6、IE7 顯示紅色 */
同時區分 Firefox、IE6、IE7:
background: orange; /* Firefox、IE8 */ *background: red !important; /* IE7 */ *background: blue; /* IE6 */
改用底線區分 IE6:
background: orange; /* Firefox、IE8 */ *background: red; /* IE7 */ _background: blue; /* IE6 */
把非 IE 瀏覽器與 IE 分開:
color: gray; /* Firefox 等非 IE 瀏覽器 */ color: red\9; /* IE8、IE9 */
<style>
div {
width: 400px;
height: 400px;
background-color: red;
background-color: blue\9; /* 所有 IE */
background-color: yellow\0; /* IE8 hack */
_background-color: #CDCDCD; /* IE6 */
*+html background-color: white; /* 僅 IE7 */
*background-color: pink; /* IE6、IE7 */
@background-color: white; /* Opera hack */
}
</style>
實務上的建議是:hack 只當作最後手段。優先順序應該是先用標準寫法把版面做對,遇到無法迴避的差異時,改用條件註解載入獨立樣式檔(可讀性遠高於在樣式中插入一堆符號),再不行才動用 hack。同時务必把 hack 寫在旁邊並加註解說明針對哪個瀏覽器,否則半年後回頭看,那些星號與底線會變成完全無法維護的謎題。