寫 CSS 時幾乎一定會撞上瀏覽器相容性問題:不同核心的瀏覽器渲染結果不同,同一瀏覽器的不同版本又常有向下相容的落差。熟悉 CSS Hack 的人看這些問題是小菜一碟,對新手而言卻往往是一大苦惱。
不過先別急著把鍋甩給瀏覽器。很多時候顯示跑掉的真正原因是 HTML 結構寫得不好,語意化沒做扎實。蓋房子得先搭鋼筋,結構穩了,Hack 才有意義。以下整理一批實用技巧。
#box { width:600px; //for ie6.0-
w\idth:500px; //for ff+ie6.0
}
#box { width:600px!important; //for ff
width:600px; //for ff+ie6.0
width /**/:500px; //for ie6.0-
}
利用子選擇器:html>body #box { }
利用 * html #box { }
使用反斜線註解:
/* \ */
#box { }
/* */
#box {
float:left;
width:100px;
margin:0 0 0 100px; //IE 會算成 200px
display:inline; //讓浮動忽略 margin 加倍
}
順帶釐清 block 與 inline 的差別:Block 元素總是從新行開始,寬高、行高、邊距都能控制;Inline 元素與其他元素排在同一行,寬高不可控。
#box {
display:block; //把內嵌元素模擬成塊元素
display:inline; //實現同行排列
display:table; //for ff,模擬 table 效果
}
@media all and (min-width:0px){ /* opera */
#box { }
}
IE 不認得 min- 這組定義,卻把正常的 width、height 當成最小值來用。結果是:只寫寬高,標準瀏覽器裡值固定不動;只寫 min-width,IE 下等於沒設。
#box { width:80px; height:35px; }
html>body #box {
width:auto; height:auto;
min-width:80px; min-height:35px;
}
#container {
min-width:600px;
width:expression(document.body.clientWidth < 600 ? "600px" : "auto");
}
第一行是正常的 CSS,第二行的 expression 只有 IE 認得,它靠 JavaScript 判斷來達成最小寬度。同樣手法也能做出最大寬度:
#container {
min-width:600px; max-width:1200px;
width:expression(document.body.clientWidth < 600 ? "600px"
: document.body.clientWidth > 1200 ? "1200px" : "auto");
}
.hackbox { display:table; } /* 當成塊級表格顯示 */
.hackbox { clear:both; }
或者用 :after 偽物件在元素後方插入清除內容。IE 不支援這個偽物件,非 IE 瀏覽器支援,因此不影響 IE/Win:
#box:after {
content:".";
display:block;
height:0;
clear:both;
visibility:hidden;
}
左側物件浮動、右側靠 margin-left 定位時,右側文字會離左邊多出 3px 間距。關鍵在最後一行:
#box { float:left; width:800px; }
#left { float:left; width:50%; }
#right { width:50%; }
* html #left { margin-right:-3px; /* 這句是關鍵 */ }
<div id="box"> <div id="left"></div> <div id="right"></div> </div>
p[id]{} div[id]{} 這種寫法對 IE6 及以下版本隱藏,Firefox 與 Opera 則正常作用。严格說這不算相容技巧,而是隱藏 CSS 的一個特性。屬性選擇器和子選擇器仍有差別:子選擇器的範圍更精確,屬性選擇器範圍較大,例如 p[id] 會命中所有帶 id 的 p 標籤。