CSS優先級簡要說明

CSS Specificity
W3C對Specificity的描述(http://www.w3.org/TR/CSS2/cascade.html#specificity):

count 1 if the declaration is from is a ‘style’ attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element’s “style” attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
count the number of ID attributes in the selector (= b)
count the number of other attributes and pseudo-classes in the selector (= c)
count the number of element names and pseudo-elements in the selector (= d)

粗略地分為a,b,c,d四級:

  • 每個元素的 style屬性(即內聯式樣),為a級1,0,0,0。
  • 每個 ID 選擇符,為b級0,1,0,0。
  • 每個 類 (class)、偽類(:hover)、屬性選擇符( [attr=” “] ),為c級0,0,1,0。
  • 每個元素(即標籤)或偽元素(如 :after),為d級0,0,0,1。
  • 其它選擇符(如 全局選擇符 * ,子選擇符 > ),為0,0,0,0。

其它規則:

  • !important 聲明的規則高於一切,如果 !important 聲明衝突,則比較優先級。
  • 如果優先級一樣,則按源碼中“後來者居上”的原則。
  • 由繼承而得到的式樣屬性不參與 specificity 的計算,低於一切其它規則(如 全局選擇符 * )。

備註:
偽類(如 :hover)值為0,0,1,0 但通常它會有個前綴,如 .class:hover值為0,0,2,0,a:hover值為0,0,1,1

參考文章:http://www.blueidea.com/tech/web/2008/5749.asp
計算權值:http://www.suzyit.com/tools/specificity.php