CSS Hack:利用瀏覽器解析 Bug/差異,針對特定瀏覽器編寫樣式。危害:代碼脆弱、維護地獄、阻礙現代特性採用、違背漸進增強。
/* 選擇器 Hack */
* html .box { } /* IE6 */
*+html .box { } /* IE7 */
html:first-child .box { } /* IE7/Opera 9 */
/* 屬性 Hack */
.box {
_width: 100px; /* IE6 (底線前綴) */
*width: 120px; /* IE6/7 (星號前綴) */
width: 100px\9; /* IE8/9 (反斜線 9) */
width: 100px\0; /* IE8-11 */
}
/* @media Hack */
@media screen\0 { .box { } } /* IE8-10 */
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { .box { } } /* IE10/11 */
/* 條件註釋 (僅 IE 支援,HTML 層面) */
/* 基礎樣式:所有瀏覽器 */
.card {
display: block;
padding: 1rem;
border: 1px solid #ddd;
}
/* 增強:支援 Flexbox 的瀏覽器 */
@supports (display: flex) {
.card {
display: flex;
gap: 1rem;
}
}
/* 進階:支援 Grid */
@supports (display: grid) {
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
}
/* 否定查詢:降級方案 */
@supports not (display: grid) {
.card-grid { display: flex; flex-wrap: wrap; }
.card-grid > * { flex: 1 1 300px; margin: 0.75rem; }
}
/* 組合查詢 */
@supports (display: grid) and (gap: 1rem) {
.grid { gap: 1rem; }
}
/* 開發時寫標準語法 */
.box {
display: flex;
transition: transform 0.3s;
user-select: none;
background: linear-gradient(45deg, red, blue);
}
/* 建置後自動產出 (視 browserslist) */
.box {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-transition: -webkit-transform 0.3s;
transition: transform 0.3s;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
background: -webkit-linear-gradient(45deg, red, blue);
background: linear-gradient(45deg, red, blue);
}
/* .browserslistrc */
# 現代專案
> 0.5% in Taiwan
last 2 versions
not dead
not IE 11
# 企業專案 (需 IE11)
> 1% in Taiwan
last 2 versions
IE 11
/* 整合工具鏈 */
- Autoprefixer: 根據矩陣自動加前綴
- Babel: 根據矩陣轉譯 JS 語法
- core-js: 根據矩陣注入最小 Polyfill
- cssnano: 根據矩陣移除無用前綴/優化
- postcss-preset-env: 根據矩陣決定 Stage 特性是否 Polyfill
| 場景 | 現代方案 | 避免 Hack 原因 |
|---|---|---|
| Safari 特有 Bug | @supports (-webkit-touch-callout: none) { } | 特性查詢而非 UA |
| Firefox 滾動條樣式 | scrollbar-width/color + ::-webkit-scrollbar 並存 | 標準化進行中 |
| 舊 Edge (EdgeHTML) | 已死,不支援 | 瀏覽器市場份額 0% |
| WebView/混合應用 | 指定目標 WebView 版本矩陣 | 可控環境,精準支援 |
_\|\\9\|\*html\|_hack