雖然現代開發已極少需針對舊 IE 撰寫 Hack,但維護老專案時仍需了解。本文整理最常見的選擇器 Hack與屬性前綴 Hack,並說明原理與風險。
| 目標 | Hack 寫法 | 範例 | 原理 |
|---|---|---|---|
| IE6 | * html .class { } |
* html .box { color: red; } |
IE6 錯誤認為 html 有父元素,匹配 * html |
| IE7 | *:first-child+html .class { } 或 *+html .class { } |
*+html .box { color: blue; } |
IE7 支援 + 相鄰選擇器,但 html 無父元素 |
| IE6/IE7 | .class { *property: value; } |
.box { *margin: 10px; } |
屬性前加 *,IE6/7 會解析,其他瀏覽器忽略 |
| IE7/現代瀏覽器 | html>body .class { } |
html>body .box { color: green; } |
IE6 不支援子選擇器 > |
| IE8+ / 現代瀏覽器 | .class { property: value\9; } |
.box { color: orange\9; } |
屬性值結尾加 \9,IE8-9 解析,現代瀏覽器忽略(IE10+ 已移除) |
| IE9+ / 現代瀏覽器 | :root .class { property: value\9; } |
:root .box { color: purple\9; } |
:root 為 html,IE9+ 支援 |
| 現代瀏覽器(非 IE) | .class { property: value; } 正常寫法,或用 @supports |
.box { color: black; } |
標準 CSS,IE 若不支援該屬性自然忽略 |
.box {
background: #000; /* 所有瀏覽器 */
*background: #00F; /* IE6/7 */
_background: #0F0; /* 僅 IE6(底線前綴) */
background: #F00\9; /* IE8/9 */
}
*:IE6/7 識別_:僅 IE6 識別(更安全)\9:IE8/9 識別(IE10+ 已移除)<!--[if IE 6]>
<link rel="stylesheet" href="ie6.css">
<![endif]-->
<!--[if lte IE 7]>
<link rel="stylesheet" href="ie7-.css">
<![endif]-->
<!--[if gt IE 8]>
<link rel="stylesheet" href="modern.css">
<![endif]-->
優點:完全隔離檔案,不污染主 CSS;缺點:IE10+ 已移除支援,需改用 JS 偵測或 @media 查詢。
@supports (display: grid) { ... } 針對支援特性的瀏覽器寫樣式。<html> 加類別(.flexbox, .no-flexbox),CSS 用類別區隔。picturefill、flexibility)。@supports 疊加進階版面。legacy-hacks.css,最後載入。Hack 是權宜之計,特性偵測與漸進增強才是長久之道。