DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
CSS Hack 大全:讓 IE6、IE7、Firefox 各顯其效
編輯:CSS詳解     

在做網站時,能否漂亮地處理各瀏覽器的差異,往往是衡量一名 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;

關鍵原理速記

掌握下面這張對照表,你就能隨心所欲地鎖定目標瀏覽器:

  • 所有 IE 都認得 *,標準瀏覽器(如 FF)不認得 *;
  • IE6 認得 *,但不認得 !important;
  • IE7 同時認得 * 與 !important;
  • FF 不認得 *,但認得 !important;
  • 補充:只有 IE6 支援底線 _,IE7 與 Firefox 均不支援。

因此,我們可以這樣一次區分三者:background:orange; *background:green; _background:blue;

切記:無論用哪種方法,書寫順序一律是「Firefox 寫前面、IE7 寫中間、IE6 寫最後」。

!important 針對 IE6

自從 IE7 支援 !important 後,這個方法如今只用來 Hack IE6(注意宣告位置要提前):

#wrapper {
  width: 100px !important; /* IE7+FF */
  width: 80px;             /* IE6 */
}

*+html 與 *html 針對 IE

*+html 與 *html 是 IE 特有的標籤寫法,Firefox 並不支援,其中 *+html 為 IE7 專屬:

#wrapper { width: 120px; }        /* Firefox */
* html #wrapper { width: 80px; }  /* IE6 */
*+html #wrapper { width: 60px; }  /* IE7,注意順序 */

要注意的是,*+html 對 IE7 生效的前提,是 HTML 頂部必須有正確的 DOCTYPE 宣告。

萬能的 float 閉合

將以下代碼加入全域 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,就能讓父容器正確包住浮動子元素。

其他常見兼容技巧

  • Firefox 中給 div 設定 padding 會使 width 與 height 增加,IE 則不會(可用 !important 解決)。
  • 垂直居中:將 line-height 設為與容器相同高度,再搭配 vertical-align:middle。
  • 水平居中:margin:0 auto(並非萬能)。
  • 若需為 a 標籤內容加樣式,需設定 display:block(常見於導航)。
  • ul 在 Firefox 下預設有 list-style 與 padding,最好事先重置。
  • 作為外層 wrapper 的 div 不要寫死高度,可加上 overflow:hidden 實現高度自適應。
  • 手形光標用 cursor:pointer,而 hand 只適用於 IE。

盒模型與 IE 特有 BUG

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; } 對症下藥。

掌握這些原理與寫法,你就能游刃有餘地面對各種瀏覽器的相容難題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved