用CSS hack技術解決瀏覽器安全色性問題

來源:互聯網
上載者:User

什麼是CSS Hack?

  不同的瀏覽器對CSS的解析結果是不同的,因此會導致相同的CSS輸出的頁面效果不同,這就需要CSS Hack來解決瀏覽器局部的相容性問題。而這個針對不同的瀏覽器寫不同的CSS 代碼的過程,就叫CSS Hack。

CSS Hack 形式

  CSS Hack大致有3種表現形式:CSS屬性Hack、CSS選擇符Hack以及IE條件注釋Hack, Hack主要針對IE瀏覽器。

  1、屬性級Hack:比如IE6能識別底線"_"和星號" * ",IE7能識別星號" * ",但不能識別底線"_",而firefox兩個都不能認識。等等

  2、選擇符級Hack:比如IE6能識別*html .class{},IE7能識別*+html .class{}或者*:first-child+html .class{}。等等

  3、IE條件注釋Hack:比如針對所有IE:<!--[if IE]><!--您的代碼--><![endif]-->,針對IE6及以下版本:<!--[if lt IE 7]><!--您的代碼--><![endif]-->,這類Hack不僅對CSS生效,對寫在判斷語句裡面的所有代碼都會生效。

  注意書寫順序:一般是將識別能力強的瀏覽器的CSS寫在後面。通常先寫FF等非IE瀏覽器所需樣式,其次寫IE8所需樣式,接著是IE7的,再接著才是IE6的。

常用CSS hack

  admin10000.com整理,以 color:red 將字型設定為紅色為例:

/* CSS屬性級Hack */color:red;    /* 所有瀏覽器可識別*/_color:red;     /*  僅IE6 識別 */*color:red;    /*  IE6、IE7 識別 */+color:red;    /*  IE6、IE7 識別 */*+color:red;    /*  IE6、IE7 識別 */[color:red;    /*  IE6、IE7 識別 */color:red\9;    /* IE6、IE7、IE8、IE9 識別 */color:red\0;    /* IE8、IE9 識別*/color:red\9\0;    /* 僅IE9識別 */color:red \0;    /* 僅IE9識別 */color:red!important; /* IE6 不識別!important 詳情參見*/-------------------------------------------------------------/* CSS選擇符級Hack */*html #demo { color:red;}   /*  僅IE6 識別 */*+html #demo { color:red;}  /*  僅IE7 識別 */body:nth-of-type(1) #demo { color:red;} /* IE9+、FF3.5+、Chrome、Safari、Opera 可以識別 */head:first-child+body #demo { color:red; } /* IE7+、FF、Chrome、Safari、Opera 可以識別 */:root #demo { color:red\9; } : /* 僅IE9識別 */--------------------------------------------------------------/* IE條件注釋Hack 詳情參見 */<!--[if IE]>此處內容只有IE可見<![endif]--> <!--[if IE 6]>此處內容只有IE6.0可見<![endif]--> <!--[if IE 7]>此處內容只有IE7.0可見<![endif]--> <!--[if gte IE 6]> IE6以及IE6以上版本可識別 <![endif]--><!--[if lt IE 7]> IE7以及IE7以下版本可識別 <![endif]--><!--[if gte IE 7]> IE7以及IE7以上版本可識別 <![endif]--><!--[if !IE]>此處內容只有非IE可見<![endif]-->

  注意:css hack雖然可以解決個瀏覽器之間css顯示的差異問題,但是畢竟不符合W3C規範,我們平時寫css最好是按照標準來,這樣對我們以後維護也是大有好處的,實在不行再用。

比較著名的css hack 相容一覽圖:http://centricle.com/ref/css/filters/
相關文檔:最全的CSS瀏覽器安全色問題

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.