主题
CSS 语法基础
说明
回顾 CSS 的核心概念和基础语法,巩固扎实的基础。
盒模型 (Box Model)
CSS 盒模型本质上是一个盒子,封装周围的 HTML 元素。它包括:边距(Margin)、边框(Border)、填充(Padding)和实际内容(Content)。
标准盒模型 vs 怪异盒模型
css
/* 标准盒模型 (content-box) - 默认 */
/* width = content */
.box-standard {
box-sizing: content-box;
}
/* 怪异盒模型 (border-box) - 推荐 */
/* width = content + padding + border */
.box-border {
box-sizing: border-box;
}最佳实践
在项目初始化时,建议将所有元素设置为 border-box,以便更好地控制布局。
css
*,
*::before,
*::after {
box-sizing: border-box;
}选择器与优先级
CSS 选择器的优先级(权重)决定了哪条规则生效。
| 选择器 | 示例 | 权重 |
|---|---|---|
!important | color: red !important | Infinity |
| 行内样式 | style="..." | 1000 |
| ID 选择器 | #header | 100 |
| 类、伪类、属性 | .btn, :hover, [type="text"] | 10 |
| 标签、伪元素 | div, ::before | 1 |
| 通配符 | * | 0 |
定位 (Position)
| 属性值 | 描述 | 参考点 |
|---|---|---|
static | 默认值 | 文档流 |
relative | 相对定位 | 自身原本的位置 |
absolute | 绝对定位 | 最近的非 static 祖先元素 |
fixed | 固定定位 | 浏览器窗口 (Viewport) |
sticky | 粘性定位 | 滚动容器 (基于阈值切换 relative/fixed) |
布局 (Layout)
Flexbox 常用属性
css
.container {
display: flex;
/* 主轴方向 */
flex-direction: row | column;
/* 换行 */
flex-wrap: nowrap | wrap;
/* 主轴对齐 */
justify-content: flex-start | center | flex-end | space-between | space-around;
/* 交叉轴对齐 */
align-items: flex-start | center | flex-end | stretch;
}Grid 常用属性
css
.container {
display: grid;
/* 定义列 */
grid-template-columns: repeat(3, 1fr); /* 3列等宽 */
/* 定义行 */
grid-template-rows: auto;
/* 间距 */
gap: 20px;
}