CSS Hack 是標準 CSS 無法達成跨瀏覽器一致時的補救手段。本文系統歸納 IE 系列、Firefox、Safari、Opera 專屬 Hack,並收錄盒模型 Hack、清除浮動 Hack 兩大經典應用模式。
| 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 及以下 |
| 屬性中註釋 | color/**/: red; | 屏蔽 IE6 |
| 選擇器與屬性雙註釋 | .box/**/ { color/**/: red; } | 屏蔽 IE5/6(IE5.5 生效) |
| 選擇器註釋 | div/**/ { color: red; } | 屏蔽 IE5 |
* html ... !important | * html .box { color: red !important; } | 僅 IE7 識別 |
| 瀏覽器 | Hack 模式 | 範例 |
|---|---|---|
| Firefox | *:lang(zh) selector { prop: val !important; } | *:lang(zh) .box { color: red !important; } |
| Safari | selector:empty { prop: val !important; } | .box:empty { color: red !important; } |
| Opera | @media all and (min-width: 0px) { selector { prop: val; } } | @media all and (min-width: 0px) { .box { color: red; } } |
.box {
width: 200px; /* IE5.x 見此值 */
voice-family: "\"}\"";
voice-family: inherit;
width: 180px; /* 正確瀏覽器見此值 */
}
利用 IE5.x 解析 voice-family 錯誤跳過後續 width。
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { zoom: 1; } /* IE6/7 觸發 hasLayout */
現代版見文章 170618。
Hack 是瀏覽器戰爭遺產,理解其原理為讀懂歷史代碼,而非新代碼指導原則。