萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Hack 完全指南:針對 IE6/7/8、Firefox 的選擇器與屬性級 Hack

早期專案需同時相容 IE6、7、8、Firefox,常需針對特定瀏覽器寫差異樣式。本文整理屬性級 Hack(Underscore、Star、Plus、9)與條件註釋兩大體系,並說明寫法順序、原理與適用版本。

屬性級 Hack 快速查閱表

Hack 寫法識別瀏覽器原理
property: value;所有瀏覽器(標準)標準屬性
property: value\9;所有 IE(IE6~IE10)IE 支援 \9 結尾
*property: value;IE6、IE7IE6/7 識別 * 前綴
_property: value;IE6IE6 識別 _ 前綴
+property: value;IE7IE7 識別 + 前綴
-property: value;IE6IE6 識別 - 前綴

實戰範例:同一屬性針對四種瀏覽器給不同顏色

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>

進階組合 Hack:同時區分 IE6/7/8/Firefox

.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 識別 - */
}

IE8 專用 Hack

.test { color:#00f\9; }       /* IE8 及以下 */
.test { color:/***/#00f\9; }   /* 僅 IE8(IE6/7 不解析 /***/)

條件註釋:載入不同 CSS 檔案(推薦做法)

<!-- 共用樣式 -->
<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 必須宣告 XHTML 1.0 Transitional

<!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,測試時請確認文檔模式。

現代建議

  • 現代專案不建議使用 Hack,改用 特性偵測、漸進增強、Polyfill
  • 若必須支援舊 IE,將 Hack 集中在獨立 ie-fix.css,以條件註釋載入,不汙染主樣式
  • IE10+ 已移除條件註釋支援,改用 @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { ... } 針對 IE10/11
copyright © 萬盛學電腦網 all rights reserved