在瀏覽器渲染引擎未統一前,CSS Hack 是解決相容性的必要手段。本文整理針對 IE 系列、Firefox、Safari、Opera 的常用 Hack 模式,供舊專案維護參考。
| 模式 | 語法範例 | 識別瀏覽器 |
|---|---|---|
屬性前加 + | +color: red; | IE 系列(含 IE7+) |
屬性前加 * | *color: red; | IE 系列(含 IE7+) |
屬性前加 _ | _color: red; | IE6 及以下(IE7 忽略) |
選擇器前綴 * html | * html .box { color: red; } | IE6 及以下 |
選擇器 html/**/ >body | html/**/ >body .box { color: red; } | IE6 及以下 |
屬性中註釋 property/**/: value | color/**/: red; | 屏蔽 IE6 |
| 選擇器與屬性雙註釋 | .box/**/ { color/**/: red; } | 屏蔽 IE5/6(IE5.5 仍生效) |
選擇器註釋 select/**/ { } | div/**/ { color: red; } | 屏蔽 IE5 |
* html selector { prop: val !important; } | * html .box { color: red !important; } | 僅 IE7 識別 |
| 瀏覽器 | Hack 模式 | 範例 |
|---|---|---|
| Firefox | 偽類 :lang + !important | *:lang(zh) .box { color: red !important; } |
| Safari | 偽類 :empty + !important | .box:empty { color: red !important; } |
| Opera | @media all and (min-width: 0px) | @media all and (min-width: 0px) { .box { color: red; } } |
.box { width: 200px; voice-family: "\"}\""; voice-family: inherit; width: 180px; }.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }legacy-ie.css),並加註解標記待移除。理解 Hack 原理有助於閱讀舊代碼,但新開發應堅持標準化、無 Hack 路徑。