詳解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表現都是一致的,都顯示藍色。
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章:- 如何使用jquery修改css中帶有!important的樣式屬性
- 原來CSS里的 !important 是如此用法