使用 position: relative 与 absolute 可实现多列布局,父容器设为 relative 形成定位上下文,子元素通过 absolute 脱离文档流并精确控制位置;例如左列固定宽、右列自适应,或扩展为两侧固定、中间自适应的三列布局,其中间列通过设置 left 和 right 实现自适应;但该方法存在脱离文档流导致内容溢出、响应式适配差、影响可访问性等问题,适用于特殊场景如弹出层,常规布局推荐使用 Flexbox 或 Grid。

使用 position: relative 和 position: absolute 可以实现多列布局,虽然现代开发更推荐 Flexbox 或 Grid,但在某些特定场景下,绝对定位仍是一种有效的控制手段。关键是理解父容器的相对定位与子元素的绝对定位之间的关系。
1. 基本原理:relative 与 absolute 配合
要实现多列布局,通常将父容器设置为 position: relative,作为定位上下文;然后将需要定位的列设置为 position: absolute,通过 left、right、width 等属性控制它们的位置和尺寸。
示例结构:
左列右列
对应 CSS:
立即学习“前端免费学习笔记(深入)”;
.container {
position: relative;
height: 400px; /* 需设定高度,否则内容可能溢出 */
}
.column-left {
position: absolute;
left: 0;
width: 200px;
top: 0;
bottom: 0;
background-color: #e0e0e0;
}
.column-right {
position: absolute;
left: 200px;
right: 0;
top: 0;
bottom: 0;
background-color: #bbdefb;
}
这样就实现了左侧固定宽度(200px)、右侧自适应的两列布局。
2. 实现三列布局(两侧固定,中间自适应)
同样方式可以扩展到三列。左右列固定宽度,中间列自动填充剩余空间。
CSS 示例:
.column-left {
position: absolute;
left: 0;
width: 150px;
top: 0;
bottom: 0;
background: #ffe0b2;
}
.column-center {
position: absolute;
left: 150px;
right: 150px;
top: 0;
bottom: 0;
background: #c8e6c9;
}
.column-right {
position: absolute;
right: 0;
width: 150px;
top: 0;
bottom: 0;
background: #b3e5fc;
}
中间列通过同时设置 left 和 right 实现自适应宽度。
3. 注意事项与限制
虽然这种方法能实现布局,但有几点需要注意:
- 父容器必须有明确的高度或确保内容不溢出,因为绝对定位会脱离文档流
- 绝对定位的元素不会影响其他元素的布局,容易造成重叠
- 响应式适配较难,不如 Flex 或 Grid 灵活
- 不利于 SEO 和可访问性,屏幕阅读器可能难以理解结构
适合用于弹出层、固定区域等特殊场景,常规页面布局建议优先考虑 display: flex 或 grid。
基本上就这些。定位方式灵活,但用起来要小心结构和兼容性。










