DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
用 !important 與符號 hack 分離 IE5/IE5.5/IE6/Firefox
編輯:CSS詳解     

同一份 CSS,在 IE6 與 Firefox 都沒問題,換到 IE5 與 IE5.5 卻亂成一團——這種情況並不少見。

網上能找到不少解法,其中「IE 條件註解」最直觀,但每個版本都要另寫一份樣式,不利於檔案精簡。以下這個做法,能把四個版本的 hack 收攏在同一處。

第一步:用 !important 把 Firefox 與 IE 分開

E1 {
  background-color: red !important;  /* 提升優先權 */
  background-color: blue;
}

在 IE6 與 Firefox 中,!important 都能提高優先級;但 IE6 的 !important 並非絕對,它會被之後的同名屬性覆蓋。於是上例在 IE6 得到 blue,在 Firefox 得到 red。這道裂縫,正好用來分流兩邊。

第二步:用符號切分 IE 自家版本

測試可以發現,>(以及 ~、`、< 等符號)只有 IE 讀得懂:

E1 {
  background-color: red;

  > background-color: blue;
}

Firefox 得到紅色,IE 得到藍色——依樣式重定義規則,能被識別才會生效,因此可證實 > 是 IE 專屬。

第三步:把 IE5.5 再剝出來

E1 {
  > /*IE only*/ background-color: black;
  > /*IE only*/ background-color /*IE5.5*/ : green;
}

IE6 得到黑色,IE5.5 得到綠色,IE5 得到黑色。第二行只有 IE5.5 認得——關鍵在屬性名稱後面那個空格。

第四步:把 IE5 剝出來

E1 {
  > /*IE only*/ background-color: red;   /* IE5 */
}
E1 /*IE5.5+*/ {
  > /*IE only*/ background-color: black;
}

E1/**/{} 這種寫法只有 IE5.5 以上版本能識別。結果:IE5 紅色,IE5.5 以上黑色。

完整範例

E1 {
  width: 500px;
  height: 50px;
  background-color: red !important;  /* FF */
  background-color: blue;            /* IE5 */
  text-align: center;
}
E1 /*IE5.5+*/ {
  > /*IE only*/ background-color: black;             /* IE6 */
  > /*IE only*/ background-color /*IE5.5*/ : green;  /* IE5.5 */
}

順序不能調動:FF → IE5 → IE6 → IE5.5。針對 IE 的定義要在屬性前加 >,因為 E1/**/{} 在 Firefox 中是能識別的。

有人會想乾脆把 FF 那行也併進去省幾個位元組。技術上可行,但 hack 終究不是標準,濫用只會讓你離標準愈來愈遠。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved