關於權重的計算,在W3C的網頁上的介紹是:
A selector’s specificity is calculated as follows
- count the number of ID selectors in the selector (= a)
- count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
- count the number of type selectors and pseudo-elements in the selector (= c)
- ignore the universal selector
翻譯一下
- id的數量為a(ex. #main #sidebar {…} 這樣是2)
- class, attr, 偽類別的數量為b
- tag跟偽元素的數量為c( li:hover:before {…} 這樣是3)
- 星號直接無視
各種selector範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* /* a=0 b=0 c=0 -> specificity = 0-0-0 */ | |
LI /* a=0 b=0 c=1 -> specificity = 0-0-1 */ | |
UL LI /* a=0 b=0 c=2 -> specificity = 0-0-2 */ | |
UL OL+LI /* a=0 b=0 c=3 -> specificity = 0-0-3 */ | |
H1 + *[REL=up] /* a=0 b=1 c=1 -> specificity = 0-1-1 */ | |
UL OL LI.red /* a=0 b=1 c=3 -> specificity = 0-1-3 */ | |
LI.red.level /* a=0 b=2 c=1 -> specificity = 0-2-1 */ | |
#x34y /* a=1 b=0 c=0 -> specificity = 1-0-0 */ | |
#s12:not(FOO) /* a=1 b=0 c=1 -> specificity = 1-0-1 */ |
計算結果的比較方式
從a比較到c,且abc各自獨立,無法進位。inline style 跟 !important 則不在計算範圍中。
inline style 跟 !important 的權重
inline style 的權重大於所有樣式表內容。!important 則是在權重計算時給予最優先權,權重越大的 !important 也會覆寫權重小的 !important。因此,在inline style中加上 !important,也會覆寫在樣式表中加的 !important,例如:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.class1 { | |
color: #f00 !important; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="class1" style="color: #0f0 !important> | |
我會是綠色 | |
</div> |