CSS中 !important 的使用

CSS中 !important 的使用

CSS的原理:

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

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

    1. <!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是识别不出来的:

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

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

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

.testClass {
color: blue !important;
}

.testClass {
color: red;
}

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

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

原文地址:https://www.cnblogs.com/1549983239yifeng/p/14351613.html