2024-06-07|
CSS布局FlexboxGrid

如何实现元素垂直居中?

整理 Flexbox、Grid、定位等常见元素垂直及水平居中方案。

方案1:Flexbox(最推荐,现代项目首选)

CSS
.parent { display: flex; align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中(可选) */ height: 300px; /* 父元素必须有高度 */ }

方案2:Grid(更简洁,但兼容性略差)

CSS
.parent { display: grid; place-items: center; /* 垂直+水平同时居中 */ height: 300px; }

原理:place-items 是 align-items 和 justify-items 的简写,center 让子项在网格单元内垂直和水平居中。

方案3:绝对定位 + transform(万能方案,兼容性好)

CSS
.parent { position: relative; height: 300px; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }

方案4:绝对定位 + margin: auto(老方案,面试常问)

原理:top: 0; bottom: 0; 让子元素在垂直方向上被拉伸,margin: auto 自动分配剩余空间。

CSS
.parent { position: relative; height: 300px; } .child { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 100px; height: 100px; }

适用场景:必须指定子元素宽高,适合固定尺寸的元素。

方案5:table-cell