CSS中!important的使用

本篇文章使用最新的 IE10 以及 firefox 与 chrome 测试(截止 2013 年 5 月 27 日 22:23:22)

CSS 的原理:

我们知道,CSS 写在不同的地方有不同的优先级, .css 文件中的定义 < 元素 style 中的属性,但是如果使用!important,事情就会变得不一样。

首先,先看下面一段代码:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>测试 Css 中的!Important 区别</title> 
</head> 
<style type="text/css">
.testClass{color:blue !important;}
</style>
<body>
    <div class="testClass" style="color:red;">
        测试 Css 中的 Important
    </div>
</body>
</html>

虽然元素的 style 中有 testClass 类的定义,但是在上面的 css 定义中的用!important 限定的定义却是优先级最高的,无论是在 ie6-10 或者 Firefox 和 Chrome 表现都是一致的,都显示蓝色。

这种情况也同时可以说明 ie6 是可以识别!important 的,只是这个是 ie6 的一个缺陷吧。如果写成下面的样式,ie6 是识别不出来的:

.testClass{ 
color:blue !important;
color:red;
}

这样,在 ie6 下展示的时候会显示成红色。

当然,也可以通过以下方式来让 ie6 识别:

.testClass{
color:blue !important;


}


.testClass{


color:red;


}

通过以上方式也是可以让 ie6 显示成蓝色的。

以上实例说明使用!important 的 css 定义是拥有最高的优先级的。只是在 ie6 下出了一点小的 bug,注意书写方式一般可以轻松避开的。