CSS (Cascading Style Sheets) 將「內容結構」與「表現樣式」徹底分離。優勢:
table、tr、input 等)。<style type="text/css"> ... </style> 置於 <head>,含 HTML 註釋兼容舊瀏覽器。<link rel="stylesheet" href="style.css" type="text/css">,多頁複用、瀏覽器快取、團隊協作友善。<p style="color:red;">,優先級最高,僅用於極少數覆蓋場景。選擇器 {
屬性1: 值1;
屬性2: 值2 值3; /* 多值空格分隔 */
}
/* 多選擇器合併 */
選擇器1, 選擇器2 { 屬性: 值; }
| 類型 | 語法 | 說明 | 範例 |
|---|---|---|---|
| 元素選擇器 | p { ... } | 針對所有指定標籤 | body {font-size:12px;} |
| 後代選擇器 | ancestor descendant { ... } | 空格表示包含關係 | table table {width:300px;} (巢狀表格) |
| 類別選擇器 | .className { ... } | HTML 加 class="className",最常用、復用性最高 | .warning {color:red;} → <p class="warning"> |
| ID 選擇器 | #idName { ... } | 頁面唯一,優先級高 | #header {background:#333;} |
h1, h2, h3 {color:navy;} 共享樣式。a:link, a:visited, a:hover, a:active (LVHA 順序)。<div class="box highlight"> 同時套用 .box 與 .highlight。input[type="text"] {border:1px solid gray;}。px (像素)、em (相對字體)、% (百分比)、pt (印刷點)、mm/cm。#RRGGBB (十六進位)、rgb(255,0,0)、rgba(...,0.5) (透明度)、關鍵字 red 等。盒模型:Content → Padding → Border → Margin。box-sizing: border-box 讓 width/height 包含 padding+border,佈局更直觀。
定位:static (預設) / relative (相對自身) / absolute (相對最近定位祖先) / fixed (相對視窗) / sticky (黏著)。
:root {--primary:#007bff;} → color:var(--primary);。@media (max-width:768px) { ... }。