萬盛學電腦網

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

CSS Bug 解決大全:10 大高頻 Bug 修復技巧與最佳實踐

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 {}
Safarihtml[xmlns*=""] body:last-child {}

用法:* html #box { width:250px; } 只對 IE6 生效。

二、IE6 PNG 透明修復

* 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。

六、IE6 雙倍邊距 Bug

浮動元素設 margin 在 IE6 會加倍。修復:display:inline;(不影響塊級特性)。

七、圖片替換文字(CSS Image Replacement)

<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 關閉時文字可見。

八、IE6 不支援 min-width

<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 更重要。新專案採用現代標準,舊專案維護時靈活套用上述方案。

copyright © 萬盛學電腦網 all rights reserved