選擇器 {
屬性: 值;
屬性: 值;
}
三要素:選擇器、屬性、值。屬性與值以冒號分隔,多組屬性以分號分隔,最後一組建議也加分號。
body {
color: black;
}
body(頁面主體)color(文字顏色)blackp {
text-align: center;
color: red;
font-family: "Microsoft YaHei", sans-serif; /* 多詞值需加引號 */
}
p {
text-align: center;
color: black;
font-family: arial;
}
相同樣式套用多個選擇器,用逗號分隔:
h1, h2, h3, h4, h5, h6 { color: green; }
p, table { font-size: 9pt; }
等效於分別撰寫,減少重複代碼。
同一 HTML 標籤套用不同样式,在自訂類名前加 .:
p.right { text-align: right; }
p.center { text-align: center; }
HTML 引用:
<p class="right">靠右對齊</p>
<p class="center">置中對齊</p>
.center { text-align: center; }
可套用於任何元素:<div class="center">、<td class="center"> 等。類名建議以功能/語意命名(如 .text-center、.btn-primary)。
頁面唯一元素,用 # 開頭:
#header {
margin: 10px 15px;
background: #333 url(images/header.jpg);
}
HTML:<div id="header">。同一頁面 ID 不可重複。
#header h1 { color: white; } /* #header 內的所有 h1 */
.sidebar a { text-decoration: none; }
| 選擇器 | 說明 |
|---|---|
a:link | 未訪問連結 |
a:visited | 已訪問連結 |
a:hover | 滑鼠懸停 |
a:active | 點擊瞬間 |
p:first-child | 父元素第一個子元素為 p |
p::first-line | 第一行文字 |
p::first-letter | 第一個字母 |
::before / ::after | 插入內容(需 content) |
practice.html + style.css,用 <link rel="stylesheet" href="style.css"> 引入。.highlight 黃底黑字、用 #footer 固定底部版權樣式。.main-nav)。!important,破壞層疊優先序。