針對 IE6、IE7、IE8、Firefox 四大瀏覽器環境的 CSS Hack 寫法整理,包含屬性前綴、選擇器 Hack、條件註釋三大體系,並說明各 Hack 的識別原理與寫法順序。
必須宣告 XHTML 1.0 Transitional DOCTYPE,否則進入 Quirks Mode 導致 Hack 失效:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
注意:IE8 相容模式 = IE7 行為。
| 目標 | 寫法 | 生效瀏覽器 | 原理 |
|---|---|---|---|
| 區分 IE6/7 vs FF/IE8 | background:blue; *background:orange; | IE6/7:orange FF/IE8:blue | FF/IE8 不識別 * 前綴 |
| 區分 IE6 vs IE7/8/FF | background:green; _background:blue; | IE7/8/FF:green IE6:blue | 僅 IE6 識別 _ 前綴 |
| 三-way 區分 FF/IE8、IE7、IE6 | background:orange; +background:green; -background:blue; | FF/IE8:orange IE7:green IE6:blue | IE6 識別 -,IE7 識別 +,FF/IE8 皆不識別 |
| 替代三-way 寫法 | background:orange; *background:green !important; *background:blue; | FF/IE8:orange IE7:green IE6:blue | IE7 識別 * 且支援 !important,IE6 識別 * 但忽略 !important |
.test {
color: #00f\9; /* IE8 及以下 */
color: /***/ #00f\9; /* 僅 IE8(IE6/7 不解析 /***/ 註釋) */
}
.test {
color: #000; /* Firefox、現代瀏覽器 */
color: #00f\9; /* IE8 */
*color: #f00; /* IE7 */
_color: #0f0; /* IE6 */
}
<link rel="stylesheet" href="css/style.css">
<!--[if IE 6]>
<link rel="stylesheet" href="css/IE6style.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" href="css/IE7style.css">
<![endif]-->
<!--[if gte IE 8]>
<link rel="stylesheet" href="css/IE8style.css">
<![endif]-->
<!--[if IE 6]><style> #warp{ padding-bottom:11px; } </style><![endif]-->
<!--[if IE 7]><style> #warp{ padding-bottom:11px; } </style><![endif]-->
<!--[if IE 8]><style> #warp{ padding-bottom:11px; } </style><![endif]-->
ie-fix.css,以條件註釋載入@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { ... }