居中布局 10 种写法:文字、图片、盒子全部覆盖
居中布局 10 种写法:文字、图片、盒子全部覆盖
居中是前端面试必考、工作必用的高频操作。但"居中"分三种对象、多种场景,写法各不相同。
本文一次性讲完10 种居中方案,按场景分类,直接复制能用。
先搞清三种居中对象
| 对象 | 核心需求 | 难度 |
|---|---|---|
| 文字/行内内容 | 水平居中 | ⭐ |
| 图片/行内块 | 水平居中(有时垂直) | ⭐⭐ |
| 盒子/块级元素 | 水平 + 垂直都居中 | ⭐⭐⭐ |
10 种写法,逐一来
①text-align: center— 文字水平居中(最经典)
适用: 文字、行内元素、图片(图片本质也是行内块)
css
.parent { text-align: center; }html
<div class="parent"> <p>这段文字居中了</p> <img src="cat.jpg" alt="图片也居中了"> </div>✅ 最简单、最常用。
❌ 只管水平,不管垂直。
②margin: 0 auto— 块级元素水平居中
适用: 有固定宽度的盒子
css
.box { width: 400px; margin: 0 auto; }html
<div class="box">我是一个居中的盒子</div>✅ 兼容所有浏览器,不需要新特性。
❌必须有宽度,宽度用auto无效。只管水平。
③Flexbox完美居中 — 水平 + 垂直(首选方案)
适用: 几乎所有居中场景,文字、图片、盒子通吃
css
.parent { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ height: 300px; }html
<div class="parent"> <div>我是盒子,我居中了</div> </div>✅ 一行代码解决水平+垂直,子元素是什么都行。
✅ 当前项目最推荐的方案。
❌ IE10 以下不支持。
④Grid居中 — 比 Flex 更短
适用: 同样通吃,写法更少
css
.parent { display: grid; place-items: center; /* 水平+垂直一步到位 */ height: 300px; }html
<div class="parent"> <div>我也居中了</div> </div>✅ 只需一行
place-items: center。
✅ Flex 和 Grid 都是现代方案,选哪个都行。
⑤line-height— 单行文字垂直居中
适用: 单行文字,高度已知
css
.box { height: 50px; line-height: 50px; text-align: center; }html
<div class="box">单行文字垂直居中</div>✅ 极简,不需要任何新特性。
❌多行文字会乱,只适合单行。
⑥padding撑开 — 盒子内部内容居中
适用: 不确定内容高度,但希望内容在盒子内居中
css
.box { padding: 20px; text-align: center; }✅ 不需要知道内容多高。
❌ 本质不是"居中",是"留白"。内容还是靠顶部对齐,只是被撑开了。
⑦position: absolute + transform— 精准居中(万能方案)
适用: 任何情况下的水平+垂直居中,不依赖父元素
css
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }html
<div class="parent" style="position: relative; height: 300px;"> <div class="child">我在正中间</div> </div>✅ 不需要知道子元素宽高,也不需要父元素是 Flex/Grid。
✅ 弹窗、浮层、Loading 图标最常用这个。
❌ 父元素必须position: relative(或其他非 static)。
⑧position: absolute + inset: 0 + margin: auto
适用: 已知宽高的盒子,绝对定位居中
css
.child { position: absolute; inset: 0; margin: auto; width: 200px; height: 100px; }✅ 写起来比 transform 更直观。
❌ 必须知道宽高。
⑨ 表格布局vertical-align: middle— 图片垂直居中
适用: 图片和文字并排,图片垂直对齐
css
.parent { display: table-cell; vertical-align: middle; text-align: center; height: 200px; }html
<div class="parent"> <img src="cat.jpg" alt="图片垂直居中"> </div>✅ 兼容老浏览器。
❌ 现在有 Flex,这个写法基本可以退役了。
⑩writing-mode— 竖排文字居中(冷门但有用)
适用: 中文竖排场景(如古籍、书法展示页)
css
.vertical-text { writing-mode: vertical-rl; text-align: center; height: 300px; line-height: 300px; }html
<div class="vertical-text">竖排文字居中</div>✅ 唯一能正确处理竖排居中的方案。
❌ 极少用到,但遇到就是救命。
一张表总结:该用哪个?
| 场景 | 推荐方案 | 备选 |
|---|---|---|
| 文字/图片水平居中 | ①text-align: center | — |
| 有宽度的盒子水平居中 | ②margin: 0 auto | Flex |
| 盒子水平+垂直居中 | ③ Flex / ④ Grid | ⑦ transform |
| 单行文字垂直居中 | ⑤line-height | Flex |
| 弹窗/浮层居中 | ⑦transform | ⑧margin: auto |
| 竖排文字居中 | ⑩writing-mode | — |
| 老项目兼容 | ② / ⑨ | — |
最后一句话
日常开发,记住 Flex 居中就够了。其他的知道在哪查就行。
这 10 种,够你覆盖所有居中场景。
