因為同一層次上,某些情況容易造成歧異,例如
p:first-letter {
font-size: 2em;
color: red !important;
}
p:first-letter {
font-size: 3em !important;
color: green;
}
p:first-letter {
font-size: 4em;
color: blue;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:demo46.css
功能:示範 CSS 2.1 樣式表的使用
作者:張凱慶
時間:西元 2011 年 7 月 */此例有三個完全相同的選擇器 (selector) p:first-letter ,宣告區 (declaration block) 的性質 (property) 都是設定字型大小的 font-size 與文字顏色的 color ,只有設定的數值 (value) 是不同的。
雖然我們是在範例中寫了三個完全相同的選擇器,實際的網頁不見得作者 (author) 自己會去寫相同的選擇器,但是樣式表 (style sheet) 卻可能有三種來源,除了網頁作者之外,還有使用者 (user) 與使用者代理程式 (user agent) ,也就是瀏覽器 (broswer) 。
同一份 HTML 文件既然有不同來源的樣式表,就有可能同時存在相同的選擇器,因此有許多規則,也就是各種階層會聯合判斷 HTML 文件最終的外觀樣式。基本的流程如下
- 尋找樣式規則,並判斷選取項符合 HTML文件中可用的名稱,例如元素名稱、 class 或 id 屬性名稱
- 依來源排序,依以下順序排列優先性
- 使用者 !important 宣告
- 作者 !important 宣告
- 作者宣告
- 使用者宣告
- 使用者代理程式宣告
- 若有多組宣告適用同一元素,計算各自的規格值排列優先性
- 若以上無法排出優先性,就依出現的順序排列,最晚出現的優先
上例都屬於作者的宣告,其中有兩個 !important ,分別是第 3 行的
color: red !important;
以及第 7 行的
font-size: 3em !important;
因此 <p> 的第一個字母會是紅色、 3em ,不會是樣式表中最後出現的藍色與 4em 。
我們以下面的 HTML 文件載入實際看看結果
<html>
<head>
<title>網頁標題</title>
<link rel="stylesheet" type="text/css"
href="demo46.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>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>
<!-- 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:demo45.html
功能:示範 CSS 2.1 樣式表的使用
作者:張凱慶
時間:西元 2011 年 7 月 -->瀏覽器開啟如下

| 中英文術語對照 | |
|---|---|
| 階層樣式表 | cascading style sheet |
| 階層 | cascading |
| 樣式 | style |
| 規則 | rule |
| 權重 | weight |
| 順序 | order |
| 規格 | specificity |
| 繼承 | inheritance |
| 選擇器 | selector |
| 宣告區 | declaration block |
| 性質 | property |
| 數值 | value |
| 作者 | author |
| 樣式表 | style sheet |
| 使用者 | user |
| 使用者代理程式 | user agent |
| 瀏覽器 | 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
沒有留言:
張貼留言