不同瀏覽器對 CSS 的支援與解析結果並不一致,加上樣式優先順序的規則,於是我們可以針對特定瀏覽器寫出只有它認得(或只有它不認得)的語法。這個過程就叫 CSS hack。
關鍵在於各瀏覽器的辨識能力差異:IE6 能辨識底線「_」與星號「*」,IE7 只認星號「*」而不認底線,Firefox 兩者都不認。書寫順序的一般原則是:辨識能力越強的瀏覽器,樣式寫在越後面。
!important 的作用是提高指定樣式規則的優先權。IE7 與所有標準瀏覽器都認得它,IE6 則不認。這正好可以用來區分 IE6 與其他瀏覽器:
.browserTest {
border: 20px solid #60A179 !important;
border: 20px solid #00F;
}
在 Firefox 與 IE7 中,!important 的優先級生效,顯示 #60A179;在 IE6 中!important 被忽略,於是顯示 #00F。
IE 系列都認得屬性前的星號,標準瀏覽器(如 Firefox)則不認。
區別 IE6 與 Firefox:
.browserTest {
border: 20px solid #60A179;
*border: 20px solid #00F;
}
區別 IE7、IE6 與 Firefox:
.browserTest {
border: 20px solid #60A179;
*border: 20px solid #00F !important;
*border: 20px solid #333;
}
只有 IE6 支援底線前綴,IE7 與 Firefox 都不支援:
.browserTest {
border: 20px solid #60A179;
*border: 20px solid #00F;
_border: 20px solid #333;
}
/* 順序一律是:Firefox 寫前面,IE7 寫中間,IE6 寫最後 */
* html 與 *+html 是 IE 特有的選擇器寫法,Firefox 不支援;其中 *+html 又只有 IE7 認得:
.browserTest { width:120px; } /* Firefox */
* html .browserTest { width:80px; } /* IE6 */
*+html .browserTest { width:60px; } /* IE7 */
注意:*+html 要對 IE7 生效,HTML 檔頭必須具備完整的 DOCTYPE 宣告,例如:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
#float {
float: left;
margin: 5px; /* IE 會理解為 10px */
display: inline; /* IE 於是又理解回 5px */
}
順帶一提,block 元素的特性是總在新行開始,寬、高、行高、邊距都可控制;inline 元素則與其他元素同行排列,寬高不可控。
#browserTest {
width: 650px !important;
width: 648px;
padding-left: 2px;
background: #fff;
}
IE 的盒子總寬 = width + padding + border + margin;Firefox 的盒子總寬就是 width,padding、border、margin 都算在 width 之內。所以一個 width:300px、padding:5px 的區塊,在 IE 中寬度是 310,在 Firefox 中是 300。若區塊帶有內距,建議寫成:
BOX { width: 300px !important; width: 290px; }
#container {
min-width: 600px;
width: expression(document.body.clientWidth < 600 ? "600px" : "auto");
}
第一行是標準寫法;第二行的 width 用了 JavaScript,只有 IE 認得,會讓 HTML 文件變得不那麼正規,但實際上就是靠 JS 判斷來達成最小寬度。
把以下程式碼放進全域樣式表,需要閉合浮動的 div 加上 clearfix 類別即可:
<style>
/* ClearFix */
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .clearfix { height: 1%; }
*+html .clearfix { height: 1%; }
.clearfix { display: inline-block; }
/* Hide from IE Mac */
.clearfix { display: block; }
/* End hide from IE Mac */
/* end of clearfix */
</style>
<div id="wrap">
<div class="column_left"><h1>Float left</h1></div>
<div class="column_right"><h1>Float right</h1></div>
</div>
#wrap { border: 6px #ccc solid; overflow: auto; _height: 1%; }
.column_left { float: left; width: 20%; padding: 10px; }
.column_right { float: right; width: 75%; padding: 10px; border-left: 6px #eee solid; }