CSS 居中
居中是 CSS 中最基础也最核心的技能。根据元素类型(行内/块级)和已知条件(尺寸固定/不固定),有多种实现方式。
一、水平居中
1. 行内元素
用于文本、<span>、<a>、<img> 等。
.parent {
text-align: center;
}
2. 块级元素
定宽块级元素。
.child {
width: 200px;
margin: 0 auto;
}
3. 绝对定位 + transform
无需定宽,兼容性较好。
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
4. Flex 布局 (推荐)
.parent {
display: flex;
justify-content: center;
}
二、垂直居中
1. 单行文本
设置 line-height 等于父容器高度。
.parent {
height: 50px;
line-height: 50px;
}
2. 绝对定位 + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
3. Flex 布局
.parent {
display: flex;
align-items: center;
}
三、水平垂直居中
方案 1: Flex (标准)
最推荐使用,代码简洁,兼容性好。
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
方案 2: Grid (最简)
仅需两行代码。
.parent {
display: grid;
place-items: center;
}
方案 3: Absolute + Transform (未知宽高)
适用于不使用 Flex/Grid 的场景,依靠 CSS3 变换。
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方案 4: Absolute + Margin auto
要求子元素有固定宽高,且设置了 top/bottom/left/right: 0。
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
width: 100px; /* 必须定宽 */
height: 100px; /* 必须定高 */
}
总结与选择
| 场景 | 推荐方案 | 备注 |
|---|
| 全能居中 | Flex | display: flex; justify-content: center; align-items: center; |
| 最简写法 | Grid | display: grid; place-items: center; |
| 兼容旧版 | Absolute + Transform | 不依赖 Flex,兼容性较好 |
| 定宽居中 | Margin auto | 简单,适用于普通块级流 |
常见面试题
- 如何实现一个元素水平垂直居中?
- 答出 Flex、Grid、Absolute+Transform 三种核心方案即可。
- 不固定宽高的元素如何居中?
- Flex/Grid 本身就无需宽高。
- Absolute +
transform: translate(-50%, -50%),因为百分比 translate 是相对于自身的。