早期瀏覽器廠商對 CSS 標準解析不一致,導致同樣代碼渲染差異。Hack 作為補救手段,利用解析器 Bug 或特有語法實現差異化樣式。
.box {
color: red; /* 所有瀏覽器 */
_color: blue; /* IE6- 僅識別下劃線 */
*color: green; /* IE6-7 識別星號 */
+color: yellow; /* IE7 識別加號 */
color: orange\9; /* IE8-11 識別 \9 */
}
* html .box { color: blue; } /* IE6- */
*+html .box { color: green; } /* IE7 */
html>/**/body .box { color: red; } /* 非 IE(舊 Opera/Safari) */
html/**/>body .box { color: red; } /* 同前 */
.box { color/**/: red; } /* 屏蔽 IE6 */
.selector/**/ { color: red; } /* 屏蔽 IE5 */
select/**/ { color: red; } /* 屏蔽 IE5 */
* html .box { color: red !important; } /* 僅 IE7 生效(IE6 忽略 important) */
@-moz-document url-prefix() {
.ff-only { color: red; }
}
/* 偽類 lang + important */
*:lang(zh) .ff-only { color: red !important; }
:root:not(:root:root) .safari-only { color: red; } /* 偽類嵌套 Hack */
@media not all and (min-resolution:.001dpcm) {
@supports (-webkit-appearance:none) {
.safari-only { color: red; }
}
}
@media all and (min-width: 0px) {
.opera-only { color: red; }
}
.box {
width: 300px; /* IE5.x 看到的寬度 */
voice-family: "\"}\""; voice-family: inherit;
width: 280px; /* 標準盒模型寬度 */
}
.clearfix::after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { *zoom: 1; } /* IE6/7 觸發 hasLayout */
<!--[if IE 7]>
<link rel="stylesheet" href="ie7.css">
<![endif]-->
@supports (display: grid) {
.layout { display: grid; }
}
CSS Hack 是歷史產物,現代開發應以特性檢測、標準優雅降級、構建工具自動化替代。理解 Hack 原理有助於維護舊項目,新項目堅決避免使用。