面對瀏覽器版本碎片化,開發者常採「漸進增強」策略:現代瀏覽器享用新特性,舊版 IE 做降級處理。本文整理三大經典解決方案,讓 HTML5/CSS3 網站在 IE 6~8 也能勉強跑起來。
Remy Sharp 的 html5shiv 透過 JavaScript document.createElement() 建立 HTML5 新元素(header、footer、article、section 等),使其在舊版 IE 中可被 CSS 樣式化。
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<![endif]-->
所有產品級網站仍建議引入,成本極低且效果立竿見影。
Selectivizr 為不支援的 CSS3 選擇器(如 :last-child、:nth-child、:not() 等)提供 Polyfill,讓舊版 IE 也能套用現代樣式。
<!--[if lte IE 8]>
<script src="https://cdn.bootcss.com/selectivizr/1.0.3/selectivizr-min.js"></script>
<![endif]-->
僅在舊版 IE 載入,現代瀏覽器零負擔。Modernizr 內建已包含 html5shiv,若已引用 Modernizr 可省略方案一。
在 <html> 標籤上透過條件註釋加上版本專屬 class,CSS 中即可針對性覆寫樣式,無需 JavaScript,無閃爍,效能最佳。
<!DOCTYPE html>
<!--[if lt IE 7 ]> <html class="ie6" lang="zh-TW"> <![endif]-->
<!--[if IE 7 ]> <html class="ie7" lang="zh-TW"> <![endif]-->
<!--[if IE 8 ]> <html class="ie8" lang="zh-TW"> <![endif]-->
<!--[if IE 9 ]> <html class="ie9" lang="zh-TW"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="zh-TW"> <!--<![endif]-->
.ie6 .sidebar { margin-right: -3px; } /* 修正 IE6 雙倍邊距 */
.ie7 .nav li { display: inline; zoom: 1; } /* 修正 IE7 inline-block */
.ie8 .box { border-radius: 0; } /* 移除 IE8 不支援的圓角 */
雖然 IE 市佔率已大幅下降,但企業內部系統、政府網站仍可能需支援舊版 IE。上述方案成熟穩定,部署成本低,值得納入專案標準流程。