CSS中!important的作用

2016/12/5 8:37:22   阅读:1710    发布者:1710

提升指定样式规则的应用优先权。

  • IE6及以下浏览器有个比较显式的支持问题存在,!important在同一条规则集里不生效。请看下述代码:

    示例代码:

    div { color: #f00 !important; color: #000; }

    在上述代码中,IE6及以下浏览器div的文本颜色为#000,!important并没有覆盖后面的规则;
    其它浏览器下div的文本颜色为#f00

  • IE6及以下浏览器要使!important生效,可用以下代码:

    示例代码:

    div { color: #f00 !important; } div { color: #000; }

    在上述代码中,IE6及以下浏览器中div的文本颜色表现与其它浏览器一致,都为#f00

     

  IE6及更早浏览器下,!important在同一条规则集内不生效。

示例:

 1 <!DOCTYPE html> 
 2 <html> 
 3   <head> 
 4     <title>important的使用</title> 
 5     <meta name="content-type" content="text/html; charset=UTF-8"> 
 6 <style> 
 7 .button { 
 8     position: relative; 
 9     background-color: #4CAF50; 
10     border-radius:8px; 
11     font-size: 28px; 
12     color: #FFFFFF; 
13     padding: 20px; 
14     width: 200px; 
15     text-align: center; 
16     transition-duration: 1.5s; 
17     overflow: hidden; 
18     cursor: pointer; 
19   } 
20   .button:hover{ 
21     box-shadow:0 4px 8px 0 rgba(0,0,0,0.1),0 6px 20px 0 rgba(0,0,0,0.299);   
22   } 
23  
24   .button:after { 
25     content: ""; 
26     background: #90EE90; 
27     display: block; 
28     position: absolute; 
29     padding-top: 300%; 
30     padding-left: 350%; 
31     margin-left: -20px!important; 
32     margin-top: -120%; 
33     opacity: 0; 
34     transition:1s; 
35 } 
36  
37 .button:active:after { 
38     padding: 0; 
39     margin: 0; 
40     opacity: 1; 
41     transition:0s; 
42 } 
43 </style> 
44 </head> 
45 <body> 
46  
47 <button class="button">Click Me</button> 
48 <p>第31行的margin-left设置了!important,因此后面的第39行是不能更改margin-left的值。 
50 </body> 
51 </html>