CSS Bug 是佈局開發中最頭疼的問題。整理 10 類最常見 Bug 修復方案,涵蓋瀏覽器選擇器、PNG 透明、虛線框、行內元素寬度、居中佈局、雙倍邊距、圖片替換、最小寬度、水平滾動條等核心痛點。
| 目標 | 選擇器 |
|---|---|
| IE6 及以下 | * html {} |
| IE7 及以下 | *:first-child+html {}, * html {} |
| 僅 IE7 | *:first-child+html {} |
| IE7 + 現代瀏覽器 | html>body {} |
| 僅現代瀏覽器(非 IE7) | html>/**/body {} |
| Opera 9 及以下 | html:first-child {} |
| Safari | html[xmlns*=""] body:last-child {} |
用法:* html #box { width:250px; } 只對 IE6 生效。
* html #image {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="image.png", sizingMethod="scale");
}
現代項目建議用 DD_belatedPNG.js 或直接放棄 IE6 支援。
a { outline: none; }
無障礙提醒:請改用 :focus { outline:1px dotted #999; } 保留鍵盤可見焦點。
span、a 等行內元素無法直接設寬高。修復:display:inline-block(需配合 Hack 兼容 IE6/7)或 display:block + float:left。
#wrapper { width:960px; margin:0 auto; position:relative; }
IE5 需在 body 加 text-align:center。
浮動元素設 margin 在 IE6 會加倍。修復:display:inline;(不影響塊級特性)。
<h1><span>標題文字</span></h1>
h1 { background:url(heading.png) no-repeat; width:300px; height:50px; overflow:hidden; }
h1 span { position:absolute; text-indent:-5000px; }
優勢:SEO 友好、螢幕閱讀器可讀、CSS 關閉時文字可見。
<div class="container"><div class="holder">內容</div></div>
.container { min-width:300px; }
* html .container { border-right:300px solid #fff; }
* html .holder { display:inline-block; position:relative; margin-right:-300px; }
原理:用右邊框撐開最小寬度,負邊距抵消。
body { overflow-x: hidden; }
適用於大圖/Flash 超出視口但不想出現橫向滾動條的場景。
.clearfix:after { content:"."; display:block; height:0; clear:both; visibility:hidden; }
.clearfix { display:inline-block; }
.clearfix { display:block; }
現代項目建議用 overflow:hidden 或 Flexbox 替代。
理解每個 Bug 成因,比死記 Hack 更重要。新專案採用現代標準,舊專案維護時靈活套用上述方案。