在做網站時,能否漂亮地處理各瀏覽器的差異,往往是衡量一名 DIV+CSS 架構師功力的重要指標。下面我們系統性地整理常見的 CSS Hack 寫法。
區分 IE6 與 FF:background:orange; *background:blue;
區分 IE6 與 IE7:background:green !important; background:blue;
區分 IE7 與 FF:background:orange; *background:green;
同時區分 FF、IE7、IE6:background:orange; *background:green !important; *background:blue;
掌握下面這張對照表,你就能隨心所欲地鎖定目標瀏覽器:
*,標準瀏覽器(如 FF)不認得 *;*,但不認得 !important;* 與 !important;*,但認得 !important;_,IE7 與 Firefox 均不支援。因此,我們可以這樣一次區分三者:background:orange; *background:green; _background:blue;
切記:無論用哪種方法,書寫順序一律是「Firefox 寫前面、IE7 寫中間、IE6 寫最後」。
自從 IE7 支援 !important 後,這個方法如今只用來 Hack IE6(注意宣告位置要提前):
#wrapper {
width: 100px !important; /* IE7+FF */
width: 80px; /* IE6 */
}
*+html 與 *html 是 IE 特有的標籤寫法,Firefox 並不支援,其中 *+html 為 IE7 專屬:
#wrapper { width: 120px; } /* Firefox */
* html #wrapper { width: 80px; } /* IE6 */
*+html #wrapper { width: 60px; } /* IE7,注意順序 */
要注意的是,*+html 對 IE7 生效的前提,是 HTML 頂部必須有正確的 DOCTYPE 宣告。
將以下代碼加入全域 CSS,並為需要閉合的 div 加上 clearfix 類別:
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { display: inline-block; }
/* 針對 IE Mac 隱藏 */
.clearfix { display: block; }
另一個輕量做法是替外層元素加上 overflow:auto,再補一句 _height:1% 來兼容 IE,就能讓父容器正確包住浮動子元素。
!important 解決)。line-height 設為與容器相同高度,再搭配 vertical-align:middle。margin:0 auto(並非萬能)。display:block(常見於導航)。overflow:hidden 實現高度自適應。cursor:pointer,而 hand 只適用於 IE。IE 對 min-width 的處理與標準瀏覽器不同,它會把 width 當成最小寬度。若要兼顧,可以這樣寫:
#box { width: 80px; height: 35px; }
html>body #box { width: auto; height: auto; min-width: 80px; min-height: 35px; }
此外,浮動元素在 IE 下容易出現雙倍 margin,加上 display:inline 即可修正;而 DIV 浮動導致文字產生 3 像素間距的 bug,可用 *html #left { margin-right:-3px; } 對症下藥。
掌握這些原理與寫法,你就能游刃有餘地面對各種瀏覽器的相容難題。