標籤:style class blog code java http
網頁開發中遇到不少次關於樣式另類的問題,於是想把從網上找的文章和自己想到的做一個簡單的規整。
在此推薦文章:http://www.cnblogs.com/ccdc/p/2765827.html
原則一:內嵌樣式->內部樣式->外聯樣式,優先順序依次排列
如果外聯樣式放在內部樣式後,將會覆蓋內部樣式。
ex:
<html> <head> <title>css優先順序</title> <style type="text/css"> .priority {color: #00ff00;} </style> </head> <body> <div class="priority">公告</div> </body></html><link rel="stylesheet" type="text/css" href="/Content/priority.css"><!--color:#ff0000;-->
結果:
原則二:明確指定添加樣式的元素,使有層次
ex:
<html><head> <title>css優先順序</title> <style type="text/css"> div p span.priority {color: #00ff00;}/*1*/ .priority {color: #ff0000;}/*2*/ </style></head> <body> <div ><p><span class="priority">公告</span></p></div> </body></html>
結果:寫法1要優先於寫法2。
原則三:css選取器特性
| css選取器 |
特性值 |
| id選取器:# |
100 |
| className:. |
10 |
| html標記:span |
1 |
原則二中的例子也可以這樣解釋:寫法1選取器的特性值為1+1+1+10=13,寫法1選取器的特性值為10。很明顯根據特性值的大小
可以決定寫法1要優先於寫法2。
原則四:!important
在一組樣式表中,如果樣式有聲明!important,表示優先順序高。
ex:
<html> <head> <title>css優先順序</title> <style type="text/css"> .priority {color: #ff0000;color: #0000ff !important;} </style> </head> <body> <div ><p><span class="priority">公告</span></p></div> </body></html>
體現這四個原則的例子在IE7~9,chrome,firefox,safari,搜狗,360瀏覽器都支援
五:@import
寫到這順便提一下@import ,@import與link的區別在於:@import先載入頁面再載入樣式表,link先載入樣式表再載入頁面。所以在網速慢的情況下
如果使用@import載入頁面時會出現跑版的瞬間。
@import只能載入樣式表,不能像link一樣添加rel,style等屬性。
個人不建議使用@import