
我們將四個數字依順序以 a 、 b 、 c 、 d 四個變數代替,例如
/* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */ |
原則上 a > b > c > d ,因此 1,0,0,0 勝於 0,1,0,0 ,也勝於 0,0,1,13 等。
已下列出 a 、 b 、 c 、 d 各自的條件
a
當 HTML 元素有設定 style 屬性 (attribute) 時, a=1 。
b
具有 ID 選取項 (ID selector) ,也就是井字號 # , b=1 。
c
有類別選取項 (class selector) 、屬性選性項 (attribute selector) 、擬類別選取項 (pseudo-class selector) 任一個之時, c+=1 ,也就是有一個 c 就遞增一。
d
有 HTML 元素或擬元素選取項任一個之時, d+=1 ,也就是有一個 d 就遞增一。
下面為 W3C 的 Calculating a selector's specificity 舉出的例子
* {} /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */ li {} /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */ li:first-line {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul li {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul ol+li {} /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */ h 1 + *[rel=up]{} /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */ ul ol li. red {} /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */ li. red . level {} /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */ #x 34 y {} /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */ style= "" /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */ |
假如我們有以下的 CSS 檔案
1 2 3 4 5 6 7 8 9 10 | #x 34 y { color : green ; } /* 《程式語言教學誌》的範例程式 檔名:demo45.css 功能:示範 CSS 2.1 樣式表的使用 作者:張凱慶 時間:西元 2011 年 7 月 */ |
由以下面的 HTML 文件載入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | < html > < head > < title >網頁標題</ title > < link rel = "stylesheet" type = "text/css" href = "demo45.css" > </ head > < body > < p >You ever have that feeling where you're not sure if you're awake or still dreaming?</ p > < p >A prison for your mind.</ p > < p id = "x34y" style = "color: red;" >Free your mind.</ p > < p >Believe the unbelievable.</ p > < p >There is no spoon.</ p > < p >I can only show you the door, you have to walk through it.</ p > < p >Choice. The problem is choice.</ p > < p >Then tomorrow we may all be dead, but how would that be different from any other day?</ p > < p >I have dreamed a dream, but now that dream has gone from me.</ p > < p >Choice is an illusion, created between those with power, and those without.</ p > < p >Because I choose to.</ p > < p >Everything that has a beginning has an end.</ p > </ body > </ html > <!-- 《程式語言教學誌》的範例程式 檔名:demo45.html 功能:示範 CSS 2.1 樣式表的使用 作者:張凱慶 時間:西元 2011 年 7 月 --> |
瀏覽器 (broswer) 開啟如下

雖然 demo45.css 設定的是 id 屬性為 x34y 的元素,該元素卻由於我們另行設定 style 屬性,因此文字顏色依 style 屬性設定的紅色顯示。
中英文術語對照 | |
---|---|
規格 | specificity |
元素 | element |
規則 | rule |
屬性 | attribute |
ID 選取項 | ID selector |
類別選取項 | class selector |
屬性選性項 | attribute selector |
擬類別選取項 | pseudo-class selector |
瀏覽器 | broswer |
您可以繼續參考
基本概念
單位
選取器
@import 規則
階層
元素呈現方式 display
相關目錄
CSS 2.1 快速導覽
HTML, CSS 教材
首頁
參考資料
http://www.w3.org/TR/CSS21/cascade.html
https://developer.mozilla.org/en/CSS/Getting_Started/Cascading_and_inheritance
沒有留言:
張貼留言