CSS 2.1 快速導覽 - 繼承

HTML 文件有其文件樹 (document tree) ,這意思是說 <html> 為根元素 (root element) ,其內 <head> 與 <body> 為 <html> 的子代 (child) ,其他於 <body> 內的元素則是 <body> 的子代,同時也是 <html> 的後代 (descendant)




這使 HTML 文件裡的各個元素 (element) 有上下的繼承 (inheritance) 關係,例如我們將 <body> 的樣式 (style) 設定成黑底白字,因此 <body> 內的各種元素都會以黑底白字呈現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
body {
    color: white;
    background-color: black;
}
 
div {
    color: gray;
    background-color: white;
}
 
blockquote {
    color: yellow;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:demo09.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="demo09.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>
<div>There is no spoon.</div>
<div>I can only show you the door, you have to walk
through it.</div>
<div>Choice. The problem is choice.</div>
<div>Then tomorrow we may all be dead, but how would that
be different from any other day?</div>
<blockquote>I have dreamed a dream, but now that dream has gone
from me.</blockquote>
<blockquote>Choice is an illusion, created between those with
power, and those without.</blockquote>
<blockquote>Because I choose to.</blockquote>
<blockquote>Everything that has a beginning has an end.</blockquote>
</body>
</html>
 
<!-- 《程式語言教學誌》的範例程式
     檔名:demo09.html
     功能:示範 CSS 2.1 樣式表的使用
     作者:張凱慶
     時間:西元 2011 年 7 月 -->


瀏覽器 (broswer) 開啟如下



此份 HTML 文件 <body> 元素裡有三種不同的元素,分別是 <p> 、 <div> 、 <blockquote> ,而 demo09.css 定義了 <body> 、 <div> 、 <blockquote> 的樣式。


<body> 中的所有元素都會繼承 <body> 的樣式,除非該元素有另行定義樣式。上例中, <p> 的外觀繼承了 <body> 的黑底白字, <div> 改成白底灰字,至於 <blockquote> 則是改成黃字,繼承 <body> 的黑底。


我們簡單說明繼承的觀念,實際上運用上繼承關係可能會很複雜。


中英文術語對照
文件樹document tree
根元素root element
子代child
後代descendant
元素element
繼承inheritance
樣式style


您可以繼續參考

基本概念
單位
選取器
@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

沒有留言: