日期:2014-05-17  浏览次数:20661 次

Css Hack原理及方法汇总
什么是CSS Hack呢?
为解决浏览器间的CSS兼容性问题,设计师们针对不同浏览器写不同的CSS code的过程,就是一个Hack的过程了。在这个过程中,不但要做到浏览器的兼容性,更要合理地做到CSS代码的绝对优化,尽可能少地人为制造冗余的代码,使CSS代码尽可能简练易读。

为什么要用CSS Hack呢?
通过对CSS代码的兼容性问题的解决,使得我们写出的页面能在不同的浏览器中达到统一的页面效果。

CSS Hack原理是什么?
根据不同浏览器对CSS样式的支持程度,解析结果和识别CSS的优先级不同,设计师们就可以根据这些不同浏览器的特点来书写不同的 CSS样式代码。IE6能识别下划线_和星号*,IE7能识别星号*,不能识别下划线_,而firefox两个都不能识别,如此,就可以针对 IE6.IE7和FF通过对这些特殊符号的使用写不同的代码了。

由于不同的浏览器对CSS的支持及解析结果不一样,还由于CSS中的优先级的关系。我们就可以根据这个来针对不同的浏览器来写不同的CSS。

比如 IE6能识别下划线"_"和星号" * ",IE7能识别星号" * ",但不能识别下划线"_",而firefox两个都不能认识。等等
  书写顺序,一般是将识别能力强的浏览器的CSS写在后面。下面如何写里面说得更详细些。

  比如要分辨IE6和firefox两种浏览器,可以这样写:
  <style>
  div{
  background:green; /* for firefox */
  *background:red; /* for IE6 */
  }
  </style>
  我在IE6中看到是红色的,在firefox中看到是绿色的。
  解释一下:
  上面的css在firefox中,它是认识不了后面的那个带星号的东东是什么的,于是将它过滤掉,不予理睬,解析得到的结果是:div{background:green},于是理所当然这个div的背景是绿色的。
  在IE6中呢,它两个background都能识别出来,它解析得到的结果是:div{background:green;background:red;},于是根据优先级别,处在后面的red的优先级高,于是当然这个div的背景颜色就是红色的了。
  CSS hack:区分IE6,IE7,firefox
  区别不同浏览器,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;_background:blue;
  background:orange;*background:green !important;*background:blue;
  注:IE都能识别*;标准浏览器(如FF)不能识别*;
  IE6能识别*,某些情况下不能识别 !important,
 
  IE6支持重定义中的!important,例如:
  .yuanxin {color:#e00!important;}
  .yuanxin {color:#000;}
  你将会发现定义了样式class="yuanxin"时,在IE下,字体显示为红色(#e00)。
  但不支持同一定义中的!important。例如:
  .yuanxin {color:#e00!important;color:#000}
  此时在IE6下不支持,你将会发现定义了样式class="yuanxin"时,字体显示为黑色(#000)。
  
  IE7能识别*,也能识别!important;
  FF不能识别*,但能识别!important;
  IE6 IE7 FF
  * √ √ ×
  !important × √ √

浏览器优先级别:FF<IE7<IE6,CSS hack书写顺序一般为FF IE7 IE6
测试浏览器:ie5.0 ie5.5 ie6.0 ie7.0 firefox2.0.0.11 opera9.10 safari3.04(pc)

测试过程:
[非标准类]
property\:value      /* ie5.5 */
*property:value      /* ie5.0 ie5.5 ie6.0 ie7.0*/
_property:value      /* ie5.0 ie5.5 ie6.0*/
Selector\    /* ie6.0 ie7.0 */
Selector, x:-moz-any-link      /*ff ie5.0 ie7.0*/
>Selector    /*ie5.0*/
<Selector {} /*只有IE5.0可识别*/ 
*html Selector\ {}  /*只有 IE6.0可识别*/ 
*+html Selector\ {} /*只有IE7.0可识别*/
[标准类]
property /**/:value      /*屏蔽ie6.0*/
property/**/:value      /*屏蔽ie5.0*/
*html selector      /*只对ie6及以下有效*/
*:first-child+html selector      /*只对ie7有效 */
html>/**/body selector      /*屏蔽所有ie*/

property /**/:value     /* ie5.0 ie5.5 ie7.0 ff2.0 op9.1 sf3 */        

Selector/**/    property/**/:value      /* ie5.5 ie6.0 ie7.0 ff2.0 op9.1 sf3 */
Selector/**/    property/**/:value      /* ie5.5 ie6.0 ie7.0 ff2.0 op9.1 sf3 */property /**/:value     /* ie5.0 ie5.5 ie7.0 ff2.0 op9.1 sf3 */        
Selector/**/    property/**/:value      /* ie5.5 ie6.0 ie7.0 ff2.0 op9.1 sf3 */
*:first-child+html {} * html Selector   /* ie5.0 ie5.5 ie6 */
*:first-child+html Selector      /* ie7.0 */
html[xmlns*=”"] body:last-child Se