同一份樣式裡要同時安撫三個瀏覽器,靠的是幾個辨識符號的組合。以下把常用組合整理成可直接複製的形式。
只區分 IE6 與 Firefox:
background: orange;
*background: blue;
只區分 IE6 與 IE7:
background: green !important;
background: blue;
只區分 IE7 與 Firefox:
background: orange;
*background: green;
三家一次分出:
background: orange;
*background: green !important;
*background: blue;
IE 系列都讀得懂「*」,標準瀏覽器(如 Firefox)讀不懂;IE6 讀得懂「*」但讀不懂 !important;IE7 兩者都懂;Firefox 讀不懂「*」但讀得懂 !important。
IE6 IE7 Firefox
* √ √ ×
!important × √ √
再補一個底線「_」:只有 IE6 支援,IE7 與 Firefox 都不認。因此還能寫成:
background: orange;
*background: green;
_background: blue;
同樣地,書寫順序固定是 Firefox 在最前、IE7 在中間、IE6 在最後。
.p_redirect {
background-color: #3f87e4;
border: 1px solid #A3C2E0;
margin-right: 1px;
font-size: 12px !important;
font-size: 13px;
}
這段寫法就是為了兼容 IE 與 Firefox 的字級差異。IE 讀不懂 !important,於是採用最後宣告的 13px;Firefox 認得 !important 並提高其優先級,於是採用 12px。一個屬性、兩行宣告,就解決了字級分歧。
值得留意的是,這些技巧之所以有效,是因為瀏覽器對「不認得的語法」採取忽略而非報錯的態度。理解這一點,你就能自己推導出更多組合,而不必死背條目。