萬盛學電腦網

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

主流瀏覽器 CSS Hack 寫法大全與 IE 條件註釋完整指南

前言

CSS Hack 是利用瀏覽器解析 Bug 或私有語法,針對特定瀏覽器應用樣式。現代開發極力避免 Hack,改用特性檢測、漸進增強、Polyfill。本文僅供維護舊專案參考。

一、通用屬性前綴 Hack(類內部寫法)

識別規律

  • IE6/7 識別 * 前綴;標準瀏覽器忽略。
  • IE6 不識別 !important;IE7 識別。
  • IE8 識別 \9 後綴;不識別 *、+、_。
  • FF/標準瀏覽器識別 !important;不識別 *、_、+。

三種常見寫法順序(順序關鍵:越特定越後)

/* 寫法一:!important 區分 IE6/7 */
.selector {
  width: 100px;           /* 所有現代瀏覽器 */
  width: 200px\9;         /* IE8 識別 */
  *width: 300px !important; /* IE7 識別(* + !important) */
  *width: 400px;          /* IE6 識別(* 無 !important) */
  _width: 500px;          /* IE6 專屬(下劃線) */
}

/* 寫法二:下劃線區分 IE6 */
.selector {
  width: 100px;   /* 現代瀏覽器 */
  width: 200px\9; /* IE8 */
  *width: 300px;  /* IE7 */
  _width: 400px;  /* IE6 */
}

/* 寫法三:+ 號區分 IE7(較少用) */
.selector {
  width: 100px;  /* 現代 */
  width: 200px\9; /* IE8 */
  +width: 300px;  /* IE7 */
  _width: 400px;  /* IE6 */
}

二、不常見但實用的選擇器 Hack

/* 1. IE6-8、FF、Opera、Safari 都識別 */
.color1 { color: #F00; color/***/: #00F /***/; }

/* 2. IE7-8、FF、Opera、Safari 識別 */
.color2 { color: #F00; color /***/: #00F /*9**/; }

/* 3. 實用:僅 IE6-8 識別 */
.color3 { color: #F00; color/***/: #00F \9; }

/* 4. 僅 IE7-8 識別 */
.color4 { color: #F00; color /***/: #00F\9; } /* color 和 /***/ 有空格 */

三、單一瀏覽器獨立支援 Hack 速查

Hack 寫法生效瀏覽器
width: 100px\9;IE6,7,8
width: 100px !important;IE6,7,8, FF, Chrome, Safari, Edge
_width: 100px;IE6
*width: 100px;IE6,7
+width: 100px;IE6,7
*+width: 100px;IE6,7
*width: 100px !important;IE6,7
width: 100px; (無前綴)IE6,7,8, FF, Chrome, Safari, Edge

四、IE 條件註釋:官方認可、唯一安全的「Hack」

僅 IE 解析執行,其他瀏覽器視為註釋忽略。可引入獨立 CSS/JS 檔案。

基本語法

<!--[if IE]>    所有 IE 可見 <![endif]-->
<!--[if IE 6]>  僅 IE6 可見 <![endif]-->
<!--[if IE 7]>  僅 IE7 可見 <![endif]-->
<!--[if IE 8]>  僅 IE8 可見 <![endif]-->
<!--[if IE 9]>  僅 IE9 可見 <![endif]-->

版本區間判斷

<!--[if lt IE 6]>   IE6 及以下 <![endif]-->
<!--[if lte IE 6]>  IE6 及以下(含 6) <![endif]-->
<!--[if gt IE 6]>   IE6 以上(7+) <![endif]-->
<!--[if gte IE 6]>  IE6 及以上(6+) <![endif]-->
<!--[if lt IE 7]>   IE7 及以下 <![endif]-->
<!--[if gte IE 7]>  IE7 及以上 <![endif]-->
<!--[if lt IE 8]>   IE8 及以下 <![endif]-->
<!--[if gte IE 8]>  IE8 及以上 <![endif]-->
<!--[if lt IE 9]>   IE9 及以下 <![endif]-->
<!--[if gte IE 9]>  IE9 及以上 <![endif]-->

非 IE 瀏覽器可見(不符標準但實用)

<!--[if !IE]>> 非 IE 瀏覽器可見 <![endif]-->

實務範例:引入 IE 專用修補樣式表

<!--[if lt IE 9]>
  <link rel="stylesheet" href="ie8-fix.css">
  <script src="html5shiv.min.js"></script>
  <script src="respond.min.js"></script> /* Media Queries polyfill */
<![endif]-->

現代替代方案:特性檢測優於瀏覽器檢測

  • Modernizr / @supports:檢測功能支援度(如 @supports (display: grid))。
  • Polyfill:為舊瀏覽器補齊缺失 API(如 classList、fetch、IntersectionObserver)。
  • CSS 變數 + @supports:現代瀏覽器用變數,舊瀏覽器回退靜態值。
  • PostCSS Preset Env:寫標準語法,自動降級編譯。

總結

Hack 是歷史妥協產物。新專案零 Hack,舊專案逐步重構移除。條件註釋僅用於引入 Polyfill/修補樣式表,不寫具體樣式規則。

copyright © 萬盛學電腦網 all rights reserved