早期專案需同時相容 IE6、7、8、Firefox,常需針對特定瀏覽器寫差異樣式。本文整理屬性級 Hack(Underscore、Star、Plus、9)與條件註釋兩大體系,並說明寫法順序、原理與適用版本。
| Hack 寫法 | 識別瀏覽器 | 原理 |
|---|---|---|
property: value; | 所有瀏覽器(標準) | 標準屬性 |
property: value\9; | 所有 IE(IE6~IE10) | IE 支援 \9 結尾 |
*property: value; | IE6、IE7 | IE6/7 識別 * 前綴 |
_property: value; | IE6 | IE6 識別 _ 前綴 |
+property: value; | IE7 | IE7 識別 + 前綴 |
-property: value; | IE6 | IE6 識別 - 前綴 |
p.ie {
height:60px; line-height:60px; text-align:center;
border:1px dashed #bbb; background:#f7f7f7;
color:blue; /* Firefox、Chrome、Safari、Opera、IE8+ */
color:brown\9; /* 所有 IE(IE6~IE10) */
+color:red; /* IE7 */
_color:green; /* IE6 */
}
HTML 測試:
<p class="ie">
<span style="display:block;display:none\9;">非 IE 瀏覽器:藍字</span>
<!--[if IE 8]>IE8:褐色字<![endif]-->
<!--[if IE 7]>IE7:紅字<![endif]-->
<!--[if IE 6]>IE6:綠字<![endif]-->
</p>
.test {
color:#000; /* Firefox、現代瀏覽器 */
color:#00f\9; /* IE8(利用 \9 配合 IE8 不識別 * / _) */
*color:#f00; /* IE7 */
_color:#0f0; /* IE6 */
}
/* 另一種寫法:利用 !important 差異 */
.test2 {
background:orange; /* FF/IE8 */
*background:green !important; /* IE7 識別 !important */
*background:blue; /* IE6 不識別 !important,套用此行 */
+background:green; /* IE7 也識別 + */
-background:blue; /* IE6 識別 - */
}
.test { color:#00f\9; } /* IE8 及以下 */
.test { color:/***/#00f\9; } /* 僅 IE8(IE6/7 不解析 /***/)
<!-- 共用樣式 -->
<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]-->
<!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">
否則 Hack 行為會因 Quirks Mode 而異常。另注意:IE8 相容模式 = IE7,測試時請確認文檔模式。
ie-fix.css,以條件註釋載入,不汙染主樣式@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { ... } 針對 IE10/11