萬盛學電腦網

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

CSS Hack 區分 IE6、IE7、IE8、Firefox 完整對照表與原理解析

針對 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 行為。

核心 Hack 對照表

目標寫法生效瀏覽器原理
區分 IE6/7 vs FF/IE8background:blue; *background:orange;IE6/7:orange
FF/IE8:blue
FF/IE8 不識別 * 前綴
區分 IE6 vs IE7/8/FFbackground:green; _background:blue;IE7/8/FF:green
IE6:blue
僅 IE6 識別 _ 前綴
三-way 區分 FF/IE8、IE7、IE6background: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

IE8 專用 Hack

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

單一規則集同時區分 IE8/IE7/IE6/Firefox

.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]-->

現代專案建議

  • 新專案避免使用 Hack,採用 特性偵測、漸進增強、Polyfill
  • 舊專案維護時,將 Hack 集中於 ie-fix.css,以條件註釋載入
  • IE10+ 不支援條件註釋,改用 @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { ... }
  • 考慮放棄 IE6/7 支援,大幅簡化 CSS 複雜度
copyright © 萬盛學電腦網 all rights reserved