问题:如何实现垂直居中?

垂直居中是 CSS 布局中最常见的需求之一,本文汇总多种实现方案。


核心方案

方法适用场景兼容性
Flexbox现代浏览器IE11+
Grid现代浏览器IE10+
position + transform通用IE9+
position + margin已知尺寸IE6+
table兼容老浏览器IE6+

具体实现

1. Flexbox(推荐)

/* 水平垂直居中 */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
 
/* 仅垂直居中 */
.parent {
  display: flex;
  align-items: center;
}

优点:代码简洁,兼容性好

2. Grid

.parent {
  display: grid;
  place-items: center;
}

优点:一行代码搞定

3. position + transform

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

优点:无需知道父容器尺寸

4. position + margin(已知尺寸)

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -width/2;
  margin-top: -height/2;
}

缺点:需要已知子元素尺寸

5. table 兼容老浏览器

.parent {
  display: table;
}
.child {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

优点:兼容 IE6+


方案对比

方案复杂度兼容性需知尺寸
Flexbox⭐⭐⭐
Grid⭐⭐⭐
position+transform⭐⭐⭐⭐⭐
position+margin⭐⭐⭐⭐⭐⭐⭐
table⭐⭐⭐⭐⭐⭐⭐

推荐

首选 Flexbox

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

次选 Grid

.parent {
  display: grid;
  place-items: center;
}

知识图谱


参考延伸

  • CSS Tricks: Centering in CSS
  • 垂直居中方法总结