CSS Hack 是在標準 CSS 無法達成跨瀏覽器一致渲染時,利用瀏覽器解析差異的補救手段。現代開發應優先使用特性偵測、Polyfill、優雅降級,僅在不得已時使用 Hack。
| Hack 寫法 | 識別瀏覽器 | 範例 |
|---|---|---|
+property: value; | IE 全系列 | +color: red; |
*property: value; | IE 全系列 | *color: blue; |
_property: value; | IE6 及以下(IE7 不識別) | _margin: 10px; |
* html selector { } | IE6 及以下 | * html .box { margin: 5px; } |
html/**/ > body selector { } | IE7+、現代瀏覽器(IE6 不識別) | html/**/ > body .box { } |
property/**/: value; | 屏蔽 IE6 | margin/**/: 10px; |
selector/**/ { property/**/: value; } | 屏蔽 IE5/6(不屏蔽 IE5.5) | .box/**/ { color/**/: red; } |
select/**/ { property: value; } | 屏蔽 IE5 | select/**/ { color: red; } |
* html selector { property: value !important; } | 僅 IE7 識別 | * html .box { color: red !important; } |
| 瀏覽器 | Hack 寫法 | 範例 |
|---|---|---|
| Firefox | *:lang(lang) selector { prop: value !important; } | *:lang(zh) .box { color: red !important; } |
| Safari | selector:empty { prop: value !important; } | .box:empty { color: red !important; } |
| Opera | @media all and (min-width: 0px) { selector { prop: value; } } | @media all and (min-width: 0px) { .box { color: red; } } |
.box {
width: 200px; /* IE5.x 見此寬度 */
voice-family: "\"}\""; /* IE5.x 會誤以為結束 */
voice-family: inherit; /* 現代瀏覽器恢復 */
width: 180px; /* 正確寬度(扣除 padding/border) */
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { zoom: 1; } /* 觸發 IE hasLayout */
<!--[if IE 8]><link rel="stylesheet" href="ie8.css"><![endif]--> 分離 IE 專用樣式。@supports。Hack 是歷史產物,理解其原理有助於維護舊專案,新專案請採用標準化、特性偵測為主的現代工作流。