当前位置: 移动技术网 > IT编程>网页制作>CSS > 详解CSS样式中的!important、*、_符号

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

2017年12月01日  | 移动技术网IT编程  | 我要评论

详解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表现都是一致的,都显示蓝色。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网