萬盛學電腦網

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

CSS Hack 針對 IE 瀏覽器的寫法與現代替代策略

CSS Hack 針對 IE 瀏覽器的寫法與現代替代策略

CSS Hack 是利用瀏覽器解析器 Bug 或獨有特性,針對特定瀏覽器編寫樣式的技巧。隨著 IE 退出歷史舞台,現代開發已極少需要 Hack,但理解其原理有助於維護舊專案、理解瀏覽器渲染差異、掌握漸進增強與優雅降級哲學。

經典 IE Hack 分類與語法

1. 屬性前綴 Hack(屬性級)

.selector {
    color: red;           /* 所有瀏覽器 */
    _color: blue;         /* 僅 IE6 識別 (底線前綴) */
    *color: green;        /* IE6/7 識別 (星號前綴) */
    \9color: orange;      /* IE8/9/10 識別 (反斜線 9) */
    color: blue\0/;       /* IE8/9/10/11 識別 (結尾 \0/) */
    @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
        color: purple;    /* 僅 IE10/11 (媒體查詢 Hack) */
    }
}

2. 選擇器 Hack(選擇器級)

/* IE6/7 不支援子代選擇器 > */
html > body .selector { color: red; }  /* 非 IE6/7 */

/* IE6 不支援相鄰兄弟選擇器 + */
h1 + p { color: red; }  /* 非 IE6 */

/* IE6-8 不支援 :root */
:root .selector { color: red; }  /* IE9+ */

/* IE9+ 支援 :not() */
.selector:not(:root) { color: red; }  /* IE9+ */

3. 條件註釋 — IE 專屬、最標準、推薦用於載入獨立修正檔

<!--[if IE]>
    <link rel="stylesheet" href="ie-all.css">
<![endif]-->

<!--[if IE 6]>
    <link rel="stylesheet" href="ie6.css">
<![endif]-->

<!--[if lte IE 8]>  /* IE 8 及以下 */
    <link rel="stylesheet" href="ie8-down.css">
<![endif]-->

<!--[if gt IE 9]>  /* IE 10+ */
    <link rel="stylesheet" href="ie10up.css">
<![endif]-->

<!--[if !IE]>