最简写法是父容器设 display: flex + justify-content: center + align-items: center,但需有明确高度(如 min-height: 100vh),子元素无需 margin: auto 或宽高设置。

单个子元素水平垂直居中:最简写法
直接给父容器加 display: flex + justify-content: center + align-items: center 就行,不用管子元素是 <div>、<img> 还是 <button>。
关键前提是:父容器必须有明确高度,比如 height: 100vh 或 min-height: 100vh;否则 align-items: center 在垂直方向上没效果。
- 子元素不需要设
margin: auto,也不用加width/height - 如果父容器是
<body>,记得先清掉默认margin和设置min-height: 100vh - IE10+ 支持,iOS Safari 7.1+ 没问题,老 IE(≤9)别用
多个子元素整体居中:别用 space-between
想让三个按钮并排、整组在容器里居中,不是靠 justify-content: space-between——它会让首尾贴边,视觉上偏左偏右。
正确做法是保持 justify-content: center,再用 gap 控制间距,或给子元素统一设 margin:
立即学习“前端免费学习笔记(深入)”;
-
justify-content: center确保整组水平居中 - 子元素用
margin-inline: 8px(或margin: 0 8px)分隔,避免首尾多出空白 - 如果要响应式换行,加
flex-wrap: wrap,但注意align-content: center才控制多行时的垂直居中
文字内容居中 ≠ 容器居中:别混用 text-align 和 justify-content
常见错误:给一个 <h1> 的父容器设了 display: flex,又给 <h1> 自己加 text-align: center——其实多余。
因为 text-align: center 只影响块级元素内部的行内内容(比如文字、<span>),而 justify-content: center 是对齐整个子元素本身。
- 若父容器是 flex,且
<h1>是直接子元素,只需justify-content: center就能让整个标题居中 - 若父容器不是 flex(比如普通
<div>),那就该用text-align: center作用于父容器,而不是子元素 - 多行文本垂直居中?
align-items: center不起作用,得靠line-height、padding或嵌套一层 flex
居中失效的三个高频原因
调试时发现居中没反应,大概率是以下之一:
- 父容器没设
display: flex,或者被其他样式(比如float、position: absolute)覆盖了 - 子元素用了
margin: auto但它是 inline 元素(如<span>),此时margin: auto无效 - 父容器高度为
auto,且内部没内容撑开,导致align-items: center没参考基准
Flex 居中看着简单,但真正卡住人的往往不是语法,而是容器尺寸和元素显示类型的隐含约束。动手前先确认父容器有没有高度、子元素是不是块级或 flex 项目,比反复调 justify-content 更快解决问题。



















