CSS 基礎選擇器與屬性
三種引入 CSS 的方式
<!-- 1. 外部樣式(推薦) -->
<link rel="stylesheet" href="style.css">
<!-- 2. 內部樣式 -->
<style>
h1 { color: blue; }
</style>
<!-- 3. 行內樣式(盡量避免) -->
<p style="color: red; font-size: 16px;">紅色文字</p>
選擇器
/* 元素選擇器 */
p { color: blue; } /* 所有 <p> */
/* Class 選擇器(可重複使用) */
.highlight { background: yellow; } /* class="highlight" */
/* ID 選擇器(唯一) */
#header { font-size: 24px; } /* id="header" */
/* 後代選擇器 */
nav a { color: white; } /* nav 裡面的所有 a */
/* 子選擇器(只選直接子元素) */
ul > li { list-style: none; } /* ul 的直接子 li */
/* 相鄰兄弟選擇器 */
h1 + p { font-size: 18px; } /* h1 後面的第一個 p */
/* 屬性選擇器 */
input[type="text"] { border: 1px solid #ccc; }
a[href^="https"] { color: green; } /* href 開頭是 https */
/* 偽類 */
a:hover { color: red; } /* 滑鼠移上去 */
li:first-child { font-weight: bold; } /* 第一個 li */
li:nth-child(2n) { background: #f0f0f0; } /* 偶數行 */
input:focus { border-color: blue; } /* 聚焦時 */
/* 偽元素 */
p::first-line { font-weight: bold; } /* 第一行 */
p::before { content: '▶ '; } /* 前面加文字 */
p::after { content: ' ◀'; } /* 後面加文字 */
常用屬性
/* 文字 */
color: #333; /* 文字顏色 */
font-size: 16px; /* 字體大小 */
font-weight: bold; /* 粗細:normal, bold, 100~900 */
font-family: 'Noto Sans TC', sans-serif; /* 字體 */
text-align: center; /* 對齊:left, center, right */
line-height: 1.6; /* 行高(1.6 倍字體大小) */
text-decoration: none; /* 去除底線 */
text-transform: uppercase; /* 全大寫 */
/* 背景 */
background-color: #f5f5f5;
background-image: url('bg.jpg');
background-size: cover; /* 填滿 */
background-position: center;
/* 邊框 */
border: 1px solid #ccc;
border-radius: 8px; /* 圓角 */
/* 大小 */
width: 100%;
max-width: 1200px;
height: auto;
min-height: 100vh; /* 至少佔滿畫面高度 */
/* 間距 */
padding: 16px; /* 內距 */
margin: 0 auto; /* 外距(0 上下,auto 左右居中) */
Box Model
┌─────────── margin ──────────┐
│ ┌──────── border ────────┐ │
│ │ ┌──── padding ─────┐ │ │
│ │ │ │ │ │
│ │ │ content │ │ │
│ │ │ │ │ │
│ │ └───────────────────┘ │ │
│ └─────────────────────────┘ │
└───────────────────────────────┘
/* 預設:width = content 寬度 */
/* border-box:width = content + padding + border */
* {
box-sizing: border-box; /* ← 推薦全域設定 */
}
優先順序(Specificity)
!important > 行內樣式 > ID > Class > 元素
∞ 1000 100 10 1
p { color: blue; } /* 1 */
.text { color: green; } /* 10 */
#title { color: red; } /* 100 */
p.text { color: orange; } /* 11 (1+10) */