CSS 基础教程
CSS(层叠样式表)控制 HTML 的样式——颜色、字体、间距、布局和响应式。掌握三个核心问题就能入门:
- 选什么 — 样式规则作用于哪些元素?
- 占多少 — 元素占据多大空间?
- 怎么排 — 元素如何排列在一起?
引入 CSS 的方式
外部样式(推荐):
<link rel="stylesheet" href="assets/styles/style.css" />内部样式: <style> 标签放在 <head> 中,仅适合演示。
行内样式: style="color: orange",尽量避免,结构和样式混在一起难以维护。
CSS 语法
选择器 {
属性: 值;
}选择器
| 选择器 | 示例 | 说明 |
|---|---|---|
| 标签 | h1 { } | 所有 <h1> 元素 |
| 类 | .intro { } | class="intro" 的元素 |
| ID | #profile { } | id="profile" 的元素 |
| 后代 | .post h2 { } | .post 里面的 <h2> |
| 子代 | .nav > a { } | .nav 的直接子 <a> |
| 伪类 | a:hover { } | 元素的特殊状态(如鼠标悬停) |
/* 多个类应用在一个元素上 */
<button class="button button-primary">提交</button>
.button { padding: 8px 16px; border-radius: 6px; }
.button-primary { background: #f08a24; color: white; }优先级
行内样式 > ID > 类 > 标签。同等优先级时,后面的规则覆盖前面的。
p { color: gray; } /* 最低优先级 */
.text { color: blue; } /* 中等 */
#summary { color: red; } /* 最高 */颜色
color: red; /* 关键词 */
color: #f08a24; /* 十六进制 */
color: rgb(240, 138, 36); /* RGB */
color: rgba(240, 138, 36, 0.8); /* RGBA 含透明度 */
color: hsl(30, 87%, 54%); /* HSL */盒模型
每个元素都是一个盒子:内容 → padding(内边距)→ border(边框)→ margin(外边距)。
/* 让 width 包含 padding + border,推荐全局设置 */
* { box-sizing: border-box; }.box {
width: 240px;
padding: 16px;
border: 1px solid #ddd;
margin: 24px;
}速记: margin 推远其他元素,padding 在元素内部撑开空间。
显示模式
| 值 | 行为 |
|---|---|
block | 占满整行,独占一行(div、p、h1) |
inline | 行内排列,不支持宽高(span、a) |
inline-block | 行内排列,但支持宽高 |
none | 从布局中完全移除 |
Flexbox(一维布局)
适合导航栏、按钮组、水平居中、卡片列表。
.nav {
display: flex;
gap: 16px;
justify-content: center;
align-items: center;
}
.card-list { display: flex; flex-wrap: wrap; gap: 20px; }
.card { flex: 1 1 240px; }Grid(二维布局)
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}一行实现响应式网格:
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 20px;
}定位
.relative { position: relative; top: 8px; left: 8px; }
.absolute { position: absolute; top: 0; right: 0; } /* 相对于最近的定位祖先 */
.fixed { position: fixed; bottom: 24px; right: 24px; }
.sticky { position: sticky; top: 0; }响应式布局
.layout {
display: grid;
grid-template-columns: 1fr 280px;
gap: 32px;
}
@media (max-width: 768px) {
.layout {
grid-template-columns: 1fr; /* 移动端单列 */
}
}图片处理
img {
max-width: 100%;
height: auto;
display: block; /* 消除底部间隙 */
}
.cover {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover; /* 裁剪填充 */
}CSS 变量
:root {
--color-accent: #f08a24;
--color-text: #1f2937;
--radius: 8px;
--content-width: 960px;
}
.container { max-width: var(--content-width); }
.button { background: var(--color-accent); border-radius: var(--radius); }过渡动画
.button {
transition: background 0.2s ease, transform 0.2s ease;
}
.button:hover {
background: #d97706;
transform: translateY(-1px);
}常见误区
- 固定宽度 → 用
width: min(100% - 32px, 1200px)替代 - 忘记 box-sizing → 全局设置
* { box-sizing: border-box; } - 选择器过深 →
.page .content .article .title span太脆弱,直接用类名 - 用 margin 做布局 → 改用 Flexbox 或 Grid