【CSS】关于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表现都是一致的,都显示蓝色。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值