CSS bug 是布局環節最耗神的問題。要在各種瀏覽器上都拿到一致的結果,往往需要來回試錯。廠商之間的競爭讓這件事變得更麻煩,而 IE6 與 IE7 在很多細節上的差異,更是無數 bug 的來源。以下整理 12 個最常用、也最該掌握的解法。
需要為某個瀏覽器單獨寫樣式時,這些 hack 選擇器很管用:
/* IE6 及更低版本 */
* html .yourClass { }
/* IE7 及更低版本 */
*:first-child+html .yourClass { }
* html .yourClass { }
/* 僅 IE7 */
*:first-child+html .yourClass { }
/* IE7 與現代瀏覽器 */
html>body .yourClass { }
/* 現代瀏覽器(IE7 不適用) */
html>/**/body .yourClass { }
/* Opera 9 及更低版本 */
html:first-child .yourClass { }
/* Safari */
html[xmlns*=""] body:last-child .yourClass { }
使用時把 hack 寫在正常的宣告之後,才能正確覆蓋:
#content-box { width: 300px; height: 150px; }
* html #content-box { width: 250px; }
IE6 不支援 Alpha 透明 PNG,只能用 AlphaImageLoader 滤镜繞過:
* html #image-style {
background-image: none;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="filename.png", sizingMethod="scale");
}
要注意這個滤镜會改變元素的定位行為,父元素需要設定 position: relative 才有比較穩定的表現。
Firefox 在點擊連結後會在外圍畫一圈虛線,用 outline 就能關掉:
a { outline: none; }
行內元素(span、a、strong、em)本來就該忽略 width,只有 IE6 會理你。正確做法是改成塊級:
span { width: 150px; display: block; }
#wrapper { margin: auto; position: relative; }
浮動元素的 margin 方向與容器一致時,IE6 會把 margin 算成兩倍。加上 display: inline 即可修正。
IE5.x 會把 padding 與 border 算進 width 之內。可用經典的盒模型 hack 提供兩組寬度,或用條件註解隔離樣式。
俗稱 IE 3px bug,通常發生在文字相鄰於浮動元素時。解法是為受影響的元素指定高度或改用 margin 修正。
IE 中有個 Duplicate Characters Bug,會讓浮動區塊裡的文字莫名重複一次。解法是移除註解,或改用條件式註解:
<!--[if !IE]>Put your commentary in here...<![endif]-->
用文字寫標題對螢幕閱讀器與 SEO 都更友善,視覺上又想用圖片時,可以這樣做:
<h1><span>Main heading one</span></h1>
h1 { background: url(heading-image.gif) no-repeat; }
h1 span { position: absolute; text-indent: -5000px; }
text-indent 把文字推到畫面左側 5000px 外,視覺上隱形但語意仍在。關掉 CSS 後標題依然正常顯示。
IE6 不支援 min-width,對彈性模板影響很大。除 IE6 以外的瀏覽器只需:
.container { min-width: 300px; }
要在 IE6 中模擬,需要一層外容器加一層內容器:
<div class="container">
<div class="holder">Content</div>
</div>
.container { min-width: 300px; }
* html .container { border-right: 300px solid #FFF; }
* html .holder { display: inline-block; position: relative; margin-right: -300px; }
原理是:視窗縮小時外層 div 會跟著變窄,直到被 300px 的右邊框擋住為止;內層 holder 同步停止收縮。邊框寬度就變成了最小寬度。
當你使用比視窗更寬的圖片或 Flash 時,可以在 body 上關掉橫向滾動:
body { overflow-x: hidden; }
這些技巧能救急,但別讓它們成為習慣。真正該花力氣的地方,是理解每個瀏覽器究竟在哪個屬性上算法不同——例如 IE6 不把 border 算進 width,而 Firefox 會算。先把跨瀏覽器通用的 CSS 寫好,不到最後一刻再動用 hack。這樣的程式碼才養得起、也才改得動。