不同瀏覽器渲染引擎對 CSS 規範實現程度、解析邏輯、默認樣式存在差異,導致同樣代碼產生不同視覺結果。核心策略:**優雅降級 + 漸進增強 + 現代工具鏈自動化**。
IE8+ 支援通過 `` 或 HTTP Header 強制指定渲染模式:
<!-- 頁面頭部盡早聲明 -->
<meta http-equiv="X-UA-Compatible" content="IE=7"> <!-- 強制 IE7 模式 -->
<meta http-equiv="X-UA-Compatible" content="IE=Edge"> <!-- 強制最新標準模式(推薦) -->
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> <!-- 尊重 DOCTYPE,無則 IE7 -->
| Hack 類型 | 語法示例 | 目標瀏覽器 | 原理 |
|---|---|---|---|
| 屬性前綴 | `_width: 100px;` `*width: 100px;` `\9` 後綴 | IE6 IE7 IE8/9/10 | 解析器容錯差異 |
| 選擇器前綴 | `* html .box {}` `*+html .box {}` `:root .box {}` | IE6 IE7 IE9+ / 現代瀏覽器 | 選擇器解析差異 |
| 條件註釋 | `<!--[if IE 6]>...<![endif]-->` `<!--[if lte IE 8]>...<![endif]-->` | IE5-9 | IE 專有註釋邏輯,非 CSS 標準 |
| @media Hack | `@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .box { } }` | IE10/11 | 媒體查詢特性差異 |
/* 現代統一:強制 border-box */
*, *::before, *::after { box-sizing: border-box; }
/* 老項目若無法全局:單獨給問題元素加 */
.legacy-box { box-sizing: border-box; }
/* 現代:BFC 觸發或 Flex/Grid 替代浮動 */
.clearfix::after { content: ""; display: table; clear: both; }
/* 或父級 */
.parent { display: flow-root; } /* 現代標準,建立 BFC */
.parent { overflow: hidden; } /* 簡單場景 */
/* 最佳:不用 float,改用 Flex/Grid */
.box { float: left; margin-left: 10px; display: inline; } /* IE6 修復 */
/* 現代:不寫 IE6 代碼,直接 Flex */
.transparent {
opacity: 0.5; /* 現代標準 */
filter: alpha(opacity=50); /* IE8- 專用,現可刪除 */
}
.rounded {
border-radius: 8px; /* 現代標準,IE9+ 全支援 */
/* IE8- 需 PIE.htc / background 圖片模擬,已無必要 */
}
.shadow {
box-shadow: 0 2px 8px rgba(0,0,0,.1); /* IE9+ */
/* IE8- 無原生支援,用 filter: progid:DXImageTransform.Microsoft.Shadow() 畸形濾鏡,棄用 */
}
.clickable { cursor: pointer; } /* 統一用 pointer,IE6+ 全支援 */
/* hand 僅 IE 支援,標準是 pointer */
/* small 在 Firefox ≈ 13px, IE ≈ 16px */
/* 解決:顯式指定像素/rem */
body { font-size: 16px; } /* 或 1rem */
.small-text { font-size: 0.875rem; } /* 14px */
input, select, textarea, button {
font: inherit; /* 繼承字體 */
color: inherit;
border: 1px solid #ccc;
border-radius: 4px;
padding: 0.5em 0.75em;
background: #fff;
-webkit-appearance: none; /* 移除 iOS/Safari 默認樣式 */
appearance: none;
}
.flex-container {
display: -webkit-box; /* 2009 版語法 */
display: -webkit-flex; /* 2012 版語法 */
display: -ms-flexbox; /* IE10 */
display: flex; /* 現代標準 */
}
/* 現代:直接寫 display: flex; 配合 Autoprefixer 自動補全 */
| 瀏覽器 | 市場份額(2024) | 建議 |
|---|---|---|
| IE 11 | < 0.5% (中國略高) | 企業內網強制才考慮,外網項目**直接放棄** |
| Edge (Legacy) | 0 | 已被 Chromium Edge 取代 |
| Safari 14-15 | 較高 | 需關注 `:focus-visible`、Container Queries、WebP/AVIF 支援 |
| Chrome/Firefox/Edge 最後 2 版本 | 主流 | 全功能支援,放心使用現代特性 |
CSS 兼容性治理已從「手寫 Hack 大全」進化為**「工具鏈自動化 + 特性檢測 + 明確支援矩陣」**。新項目**拒絕 IE**,擁抱現代 CSS(Grid、Flex、Container Queries、Cascade Layers、CSS 變數、原生嵌套),將精力投入到體驗創新而非修補舊坑。