在做web开发的时候,最头疼的就是处理各种浏览器兼容。尤其是ie低版本的兼容。于是各种 css hack层出不穷。类似 _ * \9 \0一类的,功能是实现的,却让本来写得很整齐的 css 代码变得乱糟糟的。其实用ie的条件注释就可以很简单的解决处理这些问题。

*2013年2月7日更新

去除示例代码中的ie10判断,经测试发现ie10无法使用ie条件注释(看来微软是下决心净身了)。

示例:

用ie条件注释实现浏览器兼容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<!--[if lt IE 7]><html class="ie6"><![endif]-->
<head>
<meta charset="utf-8">
<title>css hack</title>
<style>
.test {height: 40px; background: blue;}
.ie6 .test {background: red;}
</style>
</head>
<body>
<p class="test"></p>
</body>
</html>

上例中通过 ie的条件注释,给 html 标签加上指定的 class ,后面写样式的时候,只需前缀class锚定特定浏览器即可。

附一个jade描述版的较全的浏览器判断。

jade描述版浏览器判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
doctype 5
html
// if lt IE 7
|<html class="ie ie6 ltie9">
// if IE 7
|<html class="ie ie7 ltie9">
// if IE 8
|<html class="ie ie8 ltie9">
// if gte IE 9
|<html class="ie ie9">
head
meta(charset="utf-8")
title css hack
body
p css hack

有关jade的相关信息,可以参考这里 https://github.com/visionmedia/jade