CSS Hacks 利用瀏覽器的解析漏洞,來針對特定瀏覽器隱藏或提供樣式規則。實現瀏覽器相容主要有兩條路:條件註釋(Conditional Comments)與 CSS Hacks(選擇器 Hacks、屬性 Hacks)。本文做一份綜合整理。
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css/IE.css" />
<![endif]-->
不過 Yahoo 的內部最佳實踐並不建議使用條件註釋,因為它會增加額外的 HTTP 請求。
/* IE6 及以下 */
* html #uno { color: red }
/* IE7 */
*:first-child+html #dos { color: red }
/* IE7, FF, Saf, Opera */
html>body #tres { color: red }
/* IE8, FF, Saf, Opera(IE6、7 以外) */
html>/**/body #cuatro { color: red }
/* IE7 */
*+html #dieciocho { color: red }
/* 除 IE6-8 以外 */
:root *> #quince { color: red }
/* Firefox only 1+ */
#veinticuatro, x:-moz-any-link { color: red }
/* IE6 */
#once { _color: blue }
/* IE6, IE7 */
#doce { *color: blue; }
/* 除 IE6 以外 */
#dieciseis { color/**/: blue }
/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }
/* 僅 IE8 */
#veinte { color: blue\0; }
#test {
background-color: black; /* Firefox, Opera, IE8 */
[;background-color: green;] /* Safari, Chrome */
*background-color: blue; /* IE7 */
_background-color: red; /* IE6 */
}
選擇器 Hacks 的寫法雖然多,但只要代碼寫得夠標準,真正需要 Hack 的地方其實不多——除了 IE 偶爾搗亂,其他瀏覽器幾乎不會有問題。屬性 Hacks 混寫時要特別注意書寫次序,因為不同符號對應不同 IE 版本。值得一提的是,如今作者本人已較少使用 CSS Hacks,而是傾向用 IE 條件註釋把對應 class 套到 body 標籤上,讓樣式管理更清晰。