這份筆記把 CSS 的核心知識整理成四大塊:選擇器、樣式表、常用屬性、布局。適合當作速查表,也適合初學者按章節循序讀一遍。
1. 通用選擇器——比對所有元素。
* { font-family:"宋體"; }
2. 類型選擇器——比對指定標籤,逗號代表「或者」。
p { font-family:"宋體"; }
p1, p2 { font-family:"宋體"; }
3. Class 選擇器——比對 class 屬性。
p.code { font-family:"宋體"; }
td.fancy {
color: #f60;
background: #666;
}
上面這段的意思是:class 為 fancy 的表格儲存格會呈現灰底橘字。
<td class="fancy">
4. ID 選擇器——比對 id 屬性。
#code { font-family:"宋體"; }
#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}
行內樣式表:
<p style="color:blue;"></p>
內部樣式表:
<head>
<style type="text/css">
hr { color: sienna; }
p { margin-left: 20px; }
body { background-image: url("images/back40.gif"); }
</style>
</head>
外部樣式表:當樣式需要套用到很多頁面時,這是最理想的選擇。只要改一個檔案,整站外觀就跟著變。每個頁面用 <link> 連到樣式表:
<head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head>
優先級——就近原則:行內 > 內部 > 外部,越靠近元素的宣告優先權重越高(在選擇器權重相同的前提下)。
字型屬性:
.font1 {
font-family: verdana;
font-style: italic;
font-variant: small-caps;
font-weight: lighter;
font-size: 18pt;
color: red;
}
文本屬性速查:
color 文字顏色direction 文字方向line-height 行高letter-spacing 字元間距word-spacing 字詞間距text-align 文字對齊text-decoration 文字裝飾(底線、刪除線等)text-indent 首行縮排text-transform 大小寫轉換
.text1 {
word-spacing: 4;
letter-spacing: 4;
text-decoration: blink;
font-size: 18pt;
color: red;
}
背景屬性:
.p1 {
background-image: url(images/02.jpg);
background-repeat: no-repeat;
}
超連結的四種狀態:
a:link 尚未拜訪時a:visited 拜訪過後a:active 滑鼠按下未放開時a:hover 滑鼠滑過時
/* 這是註解 */
a:link { color:green; text-decoration:none }
a:active { color:blue; text-decoration:none }
a:visited { color:orange; text-decoration:none }
a:hover { color:red; text-decoration:underline }
撰寫順序請遵守 LVHA,否則效果會互相覆蓋。
邊距與邊框:
.p1 {
background-image: url(images/02.jpg);
background-repeat: no-repeat;
margin-left: 5em;
}
p { border: 10px double purple; }
DIV(塊級標記):
<html> <body> <h3>This is a header</h3> <p>This is a paragraph.</p> <div style="color:#00FF00"> <h3>This is a header</h3> <p>This is a paragraph.</p> </div> </body> </html>
span(行內標記):
<p><span>some text.</span>some other text.</p>
DIV 與 span 的差別:div 會造成換行,span 不會。
display 屬性:決定元素生成的框類型。
p.inline { display:inline; }
inline——在同一行內顯示none——不顯示block——換行輸出@import 合併樣式表:可以把多個 CSS 檔合併進一個主樣式表,集中管理。
@import url("base.css");
這份整理涵蓋的是 CSS 最基礎的地基。真正寫專案時,還需要補上盒模型、浮動與清除、層疊權重的精確計算,以及現代布局(Flexbox、Grid)這些內容——把它當作出發點,而非終點。