CSS Hack 是利用瀏覽器解析器 Bug 或獨有特性,針對特定瀏覽器編寫樣式的技巧。隨著 IE 退出歷史舞台,現代開發已極少需要 Hack,但理解其原理有助於維護舊專案、理解瀏覽器渲染差異、掌握漸進增強與優雅降級哲學。
.selector {
color: red; /* 所有瀏覽器 */
_color: blue; /* 僅 IE6 識別 (底線前綴) */
*color: green; /* IE6/7 識別 (星號前綴) */
\9color: orange; /* IE8/9/10 識別 (反斜線 9) */
color: blue\0/; /* IE8/9/10/11 識別 (結尾 \0/) */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
color: purple; /* 僅 IE10/11 (媒體查詢 Hack) */
}
}
/* IE6/7 不支援子代選擇器 > */
html > body .selector { color: red; } /* 非 IE6/7 */
/* IE6 不支援相鄰兄弟選擇器 + */
h1 + p { color: red; } /* 非 IE6 */
/* IE6-8 不支援 :root */
:root .selector { color: red; } /* IE9+ */
/* IE9+ 支援 :not() */
.selector:not(:root) { color: red; } /* IE9+ */
<!--[if IE]>
<link rel="stylesheet" href="ie-all.css">
<![endif]-->
<!--[if IE 6]>
<link rel="stylesheet" href="ie6.css">
<![endif]-->
<!--[if lte IE 8]> /* IE 8 及以下 */
<link rel="stylesheet" href="ie8-down.css">
<![endif]-->
<!--[if gt IE 9]> /* IE 10+ */
<link rel="stylesheet" href="ie10up.css">
<![endif]-->
<!--[if !IE]>