# 水平垂直居中
背景知识: display (opens new window), calc() (opens new window), flex (opens new window)
“44 年前我们就把人类送上月球了,但现在我们仍然无法在 CSS 中实现垂直居中。” ——James Anderson
以下的所有实现方案,笔者都在项目中验证过,每种方法都有自己的利与弊,大家可以根据具体的需求,选择最适合的方案。
display: flex+margin: auto不限定宽高
Center me, please!
display: grid不限定宽高
Center me, please!
绝对定位
position: absolute限定宽高
Center me, please!
绝对定位
position: absolute+calc()限定宽高
Center me, please!
绝对定位
position: absolute+translate不限定宽高
Center me, please!
仿 table 布局
display: table/table-cell+vertical-align: middle不限定宽高
Center me, please!
伪元素
:after+vertical-align:middle不限定宽高
Center me, please!
使用vertical-align实现居中时,居中元素display的值,必须为inline-block/inline,否则无法垂直居中,这是因为vertical-align只能用来指定行内元素(inline)或表格单元格(table-cell)元素的垂直对齐方式。更多请查看MDN vertical-align (opens new window)