CSS 布局基础(2025-2026 面试 & 日常开发必备)
1. 正常文档流(Normal Flow)
CSS 默认的布局方式称为正常流(Normal Flow / 常规流),分为两种:
- 块级格式化上下文(Block Formatting Context) → 垂直排列
- 行内格式化上下文(Inline Formatting Context) → 水平排列
1.1 display 的主要类型对比(2025-2026 仍最常用)
| display 值 |
独占一行? |
可设置宽高? |
水平排列? |
margin 上下生效? |
典型代表元素 |
2025-2026 使用频率 |
| block |
是 |
是 |
否 |
是 |
div, p, h1~h6, section… |
★★★★★ |
| inline |
否 |
否(宽高无效) |
是 |
左右生效,上下无效 |
span, a, strong, em… |
★★★★☆ |
| inline-block |
否 |
是 |
是 |
是 |
img(默认)、button |
★★★★☆ |
| none |
— |
— |
— |
— |
隐藏元素 |
★★★★☆ |
| flex |
是(容器) |
是 |
子元素水平/垂直 |
— |
现代布局首选 |
★★★★★ |
| grid |
是(容器) |
是 |
网格排列 |
— |
复杂二维布局 |
★★★★☆ |
| inline-flex |
否 |
是(内容尺寸) |
是 |
是 |
少用,行内弹性容器 |
★★☆☆☆ |
现代结论(2025-2026):
- 布局 → 优先 flex / grid
- 文字/按钮/图标等小元素 → inline-block / inline-flex
- 隐藏元素 → display: none(彻底移除) vs visibility: hidden(占位)
2. 浮动布局(float)—— 历史产物,但理解原理仍然重要
2.1 浮动核心特性(面试常考)
- 元素浮动后脱离正常文档流
- 不占空间(父元素高度塌陷)
- 向左/右移动直到碰到容器边界或其它浮动元素
- 只影响后面元素(前面元素不受影响)
- 行内元素浮动后自动变成类似 inline-block(可设置宽高)
2.2 高度塌陷 & 清除浮动(三种经典方案)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| .clearfix:after { content: ""; display: block; clear: both; }
.parent { overflow: hidden; display: flow-root; }
.parent { display: flow-root; }
|
3. 定位(position)—— 布局中最容易出问题的部分
3.1 五种定位方式对比表
| position 值 |
脱离文档流? |
参考对象 |
left/top/right/bottom 生效? |
z-index 默认 |
典型场景 |
| static |
否 |
正常文档流 |
无效 |
自动 |
默认,几乎所有元素 |
| relative |
否 |
自身原来位置 |
生效(相对偏移) |
自动 |
小范围微调、z轴覆盖、配合子absolute |
| absolute |
是 |
最近的定位祖先(非static) |
生效 |
自动 |
模态框、气泡、绝对定位元素 |
| fixed |
是 |
视口(viewport) |
生效 |
自动 |
固定导航、回到顶部、悬浮广告 |
| sticky |
否(粘性) |
最近滚动容器 + 视口 |
生效(粘性偏移) |
自动 |
粘性导航、分类标题、表格表头 |
3.2 包含块(Containing Block)规则
| 定位类型 |
包含块判定规则(从近到远) |
备注 |
| static |
最近块级祖先 |
— |
| relative |
自身(原来位置) |
— |
| absolute |
最近 position ≠ static 的祖先 → 否则是初始包含块(html) |
最常出错的地方 |
| fixed |
视口(viewport) |
transform 会破坏 |
| sticky |
最近有滚动机制的祖先 + 视口 |
必须在滚动容器内才生效 |
现代常见坑:
1 2 3 4
| .wrapper { transform: translateZ(0); }
|
3.3 层叠上下文(Stacking Context)与 z-index
创建层叠上下文的常见触发条件(按重要性排序)
| 触发条件 |
说明 |
| 根元素(html) |
默认创建层叠上下文 |
| position: absolute/fixed + z-index ≠ auto |
定位元素配合 z-index |
| opacity < 1 |
透明度小于1 |
| transform ≠ none |
任何 transform 变换 |
| filter ≠ none |
滤镜效果 |
| mix-blend-mode ≠ normal |
混合模式 |
| perspective ≠ none |
3D 透视 |
| contain: paint / layout / strict / content / size |
容器隔离属性 |
| will-change: opacity/transform/filter 等 |
性能优化属性 |
z-index 生效规则
- 只在同一个层叠上下文内比较
- 不同层叠上下文之间,后创建的上下文整体覆盖先创建的(除非显式 z-index 负值)
记忆口诀
- z-index 越大越在上
- 但只在同一个”家族”(层叠上下文)里比大小
- transform/opacity 会创建新家族
4. 布局选择快速决策表
| 需求场景 |
推荐方案 |
备选方案 |
| 垂直+水平居中(最常见) |
flex / grid |
absolute + transform |
| 固定在页面某处 |
position: fixed |
sticky(视情况) |
| 小范围偏移调整 |
position: relative |
transform: translate |
| 模态框/弹窗/气泡 |
position: absolute + fixed |
— |
| 导航吸顶/表格表头粘性 |
position: sticky |
— |
| 经典两栏/三栏布局 |
flex / grid |
float(基本淘汰) |
| 需要 z轴覆盖关系 |
合理创建层叠上下文 + z-index |
— |