当前位置 博文首页 > 详解CSS样式中的!important、*、_符号

    详解CSS样式中的!important、*、_符号

    作者:admin 时间:2021-08-17 19:01

    详解CSS样式中的!important、*、_符号

    !important、*、_其实没什么用,皆是用来设置样式的优先级,但是样式的优先级你可以自行排好其先后位置来设置,然而你还是要看懂的。

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

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

    <!DOCTYPE HTML> 
    <html> 
    <head> 
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
      <title>!Important</title>  
    </head>  
    <body> 
      <div style="color:blue !important;color:red;"> 
        呵呵 
      </div> 
    </body> 
    </html> 
    
    

    “呵呵”两字被定义了两个color,原本在color:red在color:blue之后,这两字应该是红色的,默认取最接近字体的颜色
    但是color:blue之后添加了!important,导致color:blue的优先级最高,“呵呵”两字应为蓝色,具体效果如下:

    然而,IE6并不能识别style属性中的!important符号,所以导致还是按原来的样式优先级,把“呵呵”两字搞成了红色。

    css样式中的!important、*、_符号,皆是用来设置优先级的,但是这些符号,仅在特定的浏览器中适用,具体如下:

    IE都能识别*;标准浏览器(如FF)不能识别*;

    IE6能识别*,但不能识别 !important;

    IE7能识别*,也能识别!important;

    FF不能识别*,但能识别!important;

    下划线"_", IE6支持下划线,IE7和firefox均不支持下划线。

    因此,可以在style属性中定义如下属性,来区分IE6,IE7,firefox:

    background:orange;*background:green;_background:blue;

    还可以这样来区分IE6,IE7,firefox:

    background:orange;*background:green !important;*background:blue;

    如下的代码:

    <!DOCTYPE HTML> 
    <html> 
    <head> 
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
      <title>!Important</title>  
    </head>  
    <body> 
      <div style="background:orange;*background:green !important;*background:blue;"> 
        区分IE7、IE8、火狐 
      </div> 
      <div style="background:orange;*background:green;_background:blue;"> 
        区分IE7、IE8、火狐 
      </div> 
    </body> 
    </html> 
    

    其运行效果如下:

    (1)IE7

    (2)IE8及其以上的浏览器,含火狐等。

    (3)IE6

    然而,这样的区别,仅能够自己用于调试,真正的前端编程还是应该利用JavaScript对浏览器的标识判断,来判断这些浏览器的类型。

    最后再补充一句,其实IE6仅仅是不能识别style中的!important,如果代码如下所示:

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

    无论是在ie6-10或者Firefox和Chrome表现都是一致的,都显示蓝色。

    如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

    jsjbwy