CSS Hack 是利用瀏覽器解析 Bug 或私有語法,針對特定瀏覽器應用樣式。現代開發極力避免 Hack,改用特性檢測、漸進增強、Polyfill。本文僅供維護舊專案參考。
* 前綴;標準瀏覽器忽略。!important;IE7 識別。\9 後綴;不識別 *、+、_。!important;不識別 *、_、+。/* 寫法一:!important 區分 IE6/7 */
.selector {
width: 100px; /* 所有現代瀏覽器 */
width: 200px\9; /* IE8 識別 */
*width: 300px !important; /* IE7 識別(* + !important) */
*width: 400px; /* IE6 識別(* 無 !important) */
_width: 500px; /* IE6 專屬(下劃線) */
}
/* 寫法二:下劃線區分 IE6 */
.selector {
width: 100px; /* 現代瀏覽器 */
width: 200px\9; /* IE8 */
*width: 300px; /* IE7 */
_width: 400px; /* IE6 */
}
/* 寫法三:+ 號區分 IE7(較少用) */
.selector {
width: 100px; /* 現代 */
width: 200px\9; /* IE8 */
+width: 300px; /* IE7 */
_width: 400px; /* IE6 */
}
/* 1. IE6-8、FF、Opera、Safari 都識別 */
.color1 { color: #F00; color/***/: #00F /***/; }
/* 2. IE7-8、FF、Opera、Safari 識別 */
.color2 { color: #F00; color /***/: #00F /*9**/; }
/* 3. 實用:僅 IE6-8 識別 */
.color3 { color: #F00; color/***/: #00F \9; }
/* 4. 僅 IE7-8 識別 */
.color4 { color: #F00; color /***/: #00F\9; } /* color 和 /***/ 有空格 */
| Hack 寫法 | 生效瀏覽器 |
|---|---|
width: 100px\9; | IE6,7,8 |
width: 100px !important; | IE6,7,8, FF, Chrome, Safari, Edge |
_width: 100px; | IE6 |
*width: 100px; | IE6,7 |
+width: 100px; | IE6,7 |
*+width: 100px; | IE6,7 |
*width: 100px !important; | IE6,7 |
width: 100px; (無前綴) | IE6,7,8, FF, Chrome, Safari, Edge |
僅 IE 解析執行,其他瀏覽器視為註釋忽略。可引入獨立 CSS/JS 檔案。
<!--[if IE]> 所有 IE 可見 <![endif]-->
<!--[if IE 6]> 僅 IE6 可見 <![endif]-->
<!--[if IE 7]> 僅 IE7 可見 <![endif]-->
<!--[if IE 8]> 僅 IE8 可見 <![endif]-->
<!--[if IE 9]> 僅 IE9 可見 <![endif]-->
<!--[if lt IE 6]> IE6 及以下 <![endif]-->
<!--[if lte IE 6]> IE6 及以下(含 6) <![endif]-->
<!--[if gt IE 6]> IE6 以上(7+) <![endif]-->
<!--[if gte IE 6]> IE6 及以上(6+) <![endif]-->
<!--[if lt IE 7]> IE7 及以下 <![endif]-->
<!--[if gte IE 7]> IE7 及以上 <![endif]-->
<!--[if lt IE 8]> IE8 及以下 <![endif]-->
<!--[if gte IE 8]> IE8 及以上 <![endif]-->
<!--[if lt IE 9]> IE9 及以下 <![endif]-->
<!--[if gte IE 9]> IE9 及以上 <![endif]-->
<!--[if !IE]>> 非 IE 瀏覽器可見 <![endif]-->
<!--[if lt IE 9]>
<link rel="stylesheet" href="ie8-fix.css">
<script src="html5shiv.min.js"></script>
<script src="respond.min.js"></script> /* Media Queries polyfill */
<![endif]-->
@supports (display: grid))。classList、fetch、IntersectionObserver)。Hack 是歷史妥協產物。新專案零 Hack,舊專案逐步重構移除。條件註釋僅用於引入 Polyfill/修補樣式表,不寫具體樣式規則。