不同瀏覽器對 CSS 的解析結果不同,同一段程式碼在不同瀏覽器下呈現的效果也就不同。CSS Hack 就是用來局部修正這類相容問題的手段——針對特定瀏覽器寫特定的程式碼。
1. 屬性級 Hack。利用各瀏覽器對特殊字元的識別差異。例如 IE6 能識別下劃線 _ 與星號 *,IE7 只能識別星號,Firefox 兩者都不認。
2. 選擇符級 Hack。例如 *html .class{} 只有 IE6 讀得懂,*+html .class{} 或 *:first-child+html .class{} 只有 IE7 讀得懂。
3. IE 條件註解 Hack。微軟從 IE5 起提供的非標準邏輯語句,針對所有 IE 寫成 <!--[if IE]>...<![endif]-->,針對 IE6 及以下則用 <!--[if lt IE 7]>...<![endif]-->。這類 hack 不只對 CSS 有效,註解裡的任何程式碼(JS、HTML、甚至伺服器端片段)都會被條件性執行。
條件註解只在 IE 下生效,其他瀏覽器會把它當成普通註解直接跳過。
/* CSS 屬性級 Hack */
color: red; /* 所有瀏覽器可識別 */
_color: red; /* 僅 IE6 識別 */
*color: red; /* IE6、IE7 識別 */
+color: red; /* IE6、IE7 識別 */
*+color: red; /* IE6、IE7 識別 */
color: red9; /* IE6、IE7、IE8、IE9 識別 */
color: red\0; /* IE8、IE9 識別 */
color: red9\0; /* 僅 IE9 識別 */
color: red!important; /* IE6 不識別 !important */
/* CSS 選擇符級 Hack */
*html #demo { color: red; } /* 僅 IE6 */
*+html #demo { color: red; } /* 僅 IE7 */
:root #demo { color: red9; } /* 僅 IE9 */
body:nth-of-type(1) #demo { color: red; } /* IE9+、FF3.5+、Chrome、Safari、Opera */
head:first-child+body #demo { color: red; } /* IE7+、FF、Chrome、Safari、Opera */
/* IE 條件註解 Hack */
<!--[if IE]>此處內容只有 IE 可見<![endif]-->
<!--[if IE 6]>此處內容只有 IE6 可見<![endif]-->
<!--[if !IE 7]>IE7 不識別,其他版本可識別<![endif]-->
<!--[if gt IE 6]>IE6 以上可識別<![endif]-->
<!--[if gte IE 7]>IE7 及以上可識別<![endif]-->
<!--[if lt IE 7]>低於 IE7 才可識別<![endif]-->
<!--[if lte IE 7]>IE7 及以下可識別<![endif]-->
<!--[if !IE]>此處內容只有非 IE 可見<![endif]-->
!important 常被用來區分 IE6 與 Firefox,理由是 IE6 不支援它。但這個說法並不完全正確。看這段:
<style type="text/css">
.demo{
color: red !important;
color: green;
}
</style>
<div class="demo">www.jb51.net</div>
Firefox 顯示紅色,IE6 顯示綠色——看起來 IE6 確實忽略了 !important。
但如果換成這樣:
<style type="text/css">
.demo{ color: red !important; }
.demo { color: green; }
</style>
<div class="demo">www.jb51.net</div>
IE6 卻顯示紅色。差別在於:當 !important 與其他宣告寫在同一個選擇器(同一組大括號)裡時,IE6 會無視它,讓後者覆蓋前者;但若寫在不同的規則中,IE6 反而認得它。
這個寫法在 IE7+、Firefox、Opera、Safari 都正常:
#my.c1.c2 { color: red; }
.c1.c2 { color: red; }
但在 IE6 中,後一個類名會覆蓋前一個,等於被理解成:
#my.c2 { color: red; }
.c2 { color: red; }
同理,#my.c1.c2.c3 { } 在 IE6 眼中就是 #my.c3 { },.c1.c2.c3 { } 則是 .c3 { }。
所以,當你用多類組合來實現樣式效果時,務必留意 IE6 的這個行為。最保險的做法是:不要用類組合的形式。
這些技巧在今天主要是理解歷史與維護老專案用的。新專案若已不支援 IE,應該優先使用 @supports 特性查詢與標準屬性,把 hack 降到最少——hack 寫得愈多,程式碼的可讀性與可維護性就愈差。