http://www.blogjava.net/ebecket 返还网
随笔-140  评论-11  文章-131  trackbacks-0
IE6/IE7/FF的CSS hack 浏览器兼容总结
2010-01-23 15:25

由于不同的浏览器对CSS的支持及解析结果不一样,处理的优先级不一样。针对不同的浏览器来写不同的CSS达到在不同浏览器下显示想要的效果就是css hack。先贴两个直观的对比图:


再贴一段代码:

#bgcolor {
            background:red !important; /* Firefox 等其他浏览器 */
            background:blue; /* IE6 */
            }
            *+html #bgcolor {
            background:green !important; /* IE7 */
            }

IE6 不认 !important, 也不认 *+html. 所以 IE6 只能是 blue.
IE7 认 !important, 也认 *+html, 优先度: (*+html + !important) > !important > +html. IE7 可以是 red, blue 和 green, 但 green 的优先度最高.
Firefox 和其他浏览器都认 !important. !important 优先, Firefox 可以是 red 和 blue, 但 red 优先度高。

下面以一个实际需求进行不同写法的实现:

针对下面的html代码:

<body> 
    <div><span>Text</span></div> 
</body>

  写CSS代码,分别在IE6、IE7、FF下显示不同的效果:

  简单说明一下:IE6的划线是在下边、IE7是中间、FF是上边。因为IE6兼容性最差(同时下划线_只有ie6支持),IE7标准居中,FF标准最高。

  第一种方法:

div{ 
    text-decoration:overline; 
    *text-decoration:line-through; 
    _text-decoration:underline; 
}

  原理是:


  简单地说,就是利用下面几点:

  1.各个浏览器解析CSS的语法不尽相同

  2.CSS语法规则:后面的属性覆盖前面的属性

  而这里仅仅是利用了_(IE6的专属)和*(用于IE6和IE7),接下来利用一下!important语法。

  第二种方法:

  !important语法针对的是“后面的属性覆盖前面的属性”这一语法,也就是说标识了!important的属性,是不被后面的相同属性所覆盖的,而IE6不认识这个,导致其他浏览器很容易根据这点“欺负”IE6:

div{ 
    text-decoration:overline; 
    *text-decoration:line-through!important; 
    *text-decoration:underline; 
}

  原理:

  1.FF不认识*,但IE6/IE7认识

  2.IE6不认识!imprtant,但IE7认识

  注意,顺序不能换,如果改为下面这样:

text-decoration:overline; 
*text-decoration:underline; 
*text-decoration:line-through !important;

  IE6和IE7都一样了。

  IE6是支持!important属性的(该属性为CSS1语法,支持IE4+),上面的写法只是IE6的一个bug(同一个{}里面,相同属性取后者),若想要IE6支持,一般的做法是将CSS拆分,比如:

div{
    text-decoration:line-through!important; 
}
div{
    text-decoration:underline;
}

  这样,在IE6下,显示的是line-through效果。

  第三种方法:

  先看一个表



  为了方便记忆,在上面那个hack表增加了“针对对象”一列(关于*旁边有无空格均可,可以理解其同时也作为分隔符),需要补充的是IE7的专属写法:*+html div

  在此就利用IE6和IE7的专属写法:

div{ 
    text-decoration:overline; 
} 
*+html div{ 
    text-decoration:line-through; 
} 
* html div{ 
    text-decoration:underline; 
}

  第四种方法:

div{ 
    text-decoration:overline; 
} 
html*div{ 
    text-decoration:line-through !important; 
    text-decoration:underline; 
}

  原理:利用IE6/IE7的共同专属 + IE6不懂!important

  第五种方法:

body>div{ 
    text-decoration:overline; 
    *text-decoration:line-through; 
} 
div{ 
    text-decoration:underline; 
}

  原理:利用IE6不懂>这种选择符 + 针对属性的hack。

另外还有/**/或者@important等方法。

为了通过W3C验证工具,需要把hack样式放到不同文件中处理。一个是针对所有浏览器的, 一个只为 IE 服务. 将所有符合 W3C 的代码写到一个里面去, 而一些 IE 中必须的, 又不能通过 W3C 验证的代码 (如: cursor:hand;) 放到另一个文件中, 再用下面的方法导入.

<!-- 放置所有浏览器的样式 -->
<link rel="stylesheet" href="style.css" type="text/css" />
<!-- 只放置 IE 必须的, 而不能通过 W3C 的代码 -->
<!--[if IE]>
<link rel="stylesheet" href="style_ie.css" type="text/css" />
<![endif]-->

posted on 2010-03-23 10:10 becket_zheng 阅读(283) 评论(0)  编辑  收藏 所属分类: 网页web前端技术

只有注册用户登录后才能发表评论。


网站导航: