1.CSS重置和盒模型
每个浏览器都有默认样式,导致:
-
Chrome、Firefox、Safari 显示不一致
-
按钮、链接、列表自带奇怪样式
-
边距、字体大小不统一
css
/* 第一行就要写这个! */
* {
margin: 0;
padding: 0;
box-sizing: border-box; /* 重要!让padding不影响宽度 */
}
body {
font-family: "Microsoft Yahei", sans-serif;
line-height: 1.6;
}
css
/* CSS重置 - 清除所有默认样式 */
* {
margin: 0; /* 清除所有外边距 */
padding: 0; /* 清除所有内边距 */
box-sizing: border-box; /* 重要!见下面解释 */
}
/* 额外清理常见元素 */
ul, ol { list-style: none; } /* 去掉列表点 */
a { text-decoration: none; } /* 去掉链接下划线 */
img { max-width: 100%; } /* 图片自适应 */
box-sizing: border-box; 一句话解释:
"把盒子的宽度和高度固定住,不让padding和border把盒子撑大"
写了这个就是用现代方式的盒子
css
传统:实际宽度 = 内容 + 内边距 + 边框
现代:实际宽度 = 你设置的宽度(已经包含一切)
2.CSS选择器优先级
css
/* 优先级从高到低 */
!important > 行内样式 > id选择器 > class选择器 > 标签选择器
3.Flex布局
css
.container {
display: flex; /* 开启flex布局 */
justify-content: center; /* 水平对齐 */
align-items: center; /* 垂直对齐 */
flex-direction: row; /* 方向 */
flex-wrap: wrap; /* 换行 */
}
Flex = 弹性盒子
就像一根有弹性的棍子,上面的项目可以灵活排列
主轴和交叉轴
css
.container {
display: flex;
flex-direction: row; /* 主轴水平(默认) */
}
情况1:flex-direction: row(默认)
css
主轴(main axis):从左到右 ←────────→
交叉轴(cross axis):从上到下
↓
[项目1] [项目2] [项目3]
↓
情况2:flex-direction: column
css
主轴:从上到下
交叉轴:从左到右
[项目1] ← 交叉轴 →
[项目2]
[项目3]
常用属性
1. justify-content - 主轴对齐方式(水平方向)
css
.container {
display: flex;
justify-content: ???;
}
| 值 | 效果 | 图示 |
|---|---|---|
flex-start |
靠左对齐 | [1][2][3]____________ |
flex-end |
靠右对齐 | ____________[1][2][3] |
center |
居中 | ______[1][2][3]______ |
space-between |
两端对齐,中间等距 | [1]____[2]____[3] |
space-around |
每个项目周围等距 | _[1]___[2]___[3]_ |
space-evenly |
所有间距完全相等 | _[1]_[2]_[3]_ |
2. align-items - 交叉轴对齐方式(垂直方向/竖直方向)
css
.container {
display: flex;
align-items: ???;
height: 200px; /* 必须有高度才明显 */
}
| 值 | 效果 | 图示 |
|---|---|---|
stretch |
拉伸填满(默认) | [────1────] [────2────] |
flex-start |
顶部对齐 | [1] [2] 顶部对齐 |
center |
垂直居中 | 居中 [1] [2] 居中 |
flex-end |
底部对齐 | 底部对齐 [1] [2] |
baseline |
基线对齐 | 文字基线对齐 |
3. flex-direction - 主轴方向
css
.container {
display: flex;
flex-direction: row; /* 默认:横向排列 */
/* 或:column(竖向) */
/* 或:row-reverse(反向横向) */
/* 或:column-reverse(反向竖向) */
}
4. flex-wrap - 是否换行
css
.container {
display: flex;
flex-wrap: nowrap; /* 默认:不换行(会压缩) */
/* 或:wrap(换行) */
/* 或:wrap-reverse(反向换行) */
}
justify-content |
align-items |
gap |
|
|---|---|---|---|
| 属于 | Flex布局系统 | Flex布局系统 | CSS通用属性 |
| 需要 | display: flex 才生效 |
display: flex 才生效 |
多种布局都能用 |
| 作用 | 控制整体队伍的水平位置 | 控制每个士兵的垂直位置 | 控制所有孩子之间的间距 |
| 值举例 | center, start, space-between |
center, start, stretch |
20px, 1rem, 10% |
4.调试技巧
css
/* 调试边框大法 */
* {
border: 1px solid red !important; /* 快速查看所有盒子 */
}
/* 或使用Chrome开发者工具 */
F12 → Elements → Styles → 可以实时修改CSS