父容器必须设置明确高度(如min-height: 100vh)且图片的直接父元素需设display: flex并同时声明justify-content: center和align-items: center,避免float或absolute脱离文档流。

图片父容器没设高度,flex 垂直居中会失效
用 如果图片加了 常见结构是: 立即学习“前端免费学习笔记(深入)”; 实际能跑通的最小代码就是这四行,其余都是干扰项。真正卡住的,往往不是 flex 写错了,而是容器链断在某个看不见的地方。display: flex 居中图片时,如果父容器是 height 或内容撑不开,align-items: center 就没效果——因为容器高度为 0,没有“垂直方向可居中的空间”。
height: 300px、min-height: 100vh,或被其他内容撑开min-height: 100vh 更稳妥height: auto + flex 期待垂直居中,这是新手最常卡住的点忘记写 justify-content 和 align-items 两个属性
flex 水平垂直居中必须同时设置:水平靠 justify-content: center,垂直靠 align-items: center。漏掉任一个,就只能单向居中。.container {
display: flex;
justify-content: center; /* 水平 */
align-items: center; /* 垂直 */
min-height: 100vh;
}
justify-content 控制主轴(默认是水平),align-items 控制交叉轴(默认是垂直)flex-direction: column,两者的含义会互换,但新手项目里通常不改,默认即可align-content——它只对多行 flex 容器起作用,单张图片用不到图片本身设置了 float 或 position: absolute
float: left 或 position: absolute,它就脱离了 flex 流,justify-content 和 align-items 对它完全无效。
img { float: left }
img { float: none; position: static; } 排查position 或 float
父容器不是直接包裹 img 的那个元素
。如果只给最外层 .wrapper 加 flex,但中间多了一层没设高度/没参与布局的
justify-content 和 align-items 是否生效在它的**直接父容器**上display: flex,而不是隔一层再设display: contents 让中间层“消失”(注意兼容性:IE 不支持)










