垂直水平居中方案

CSS 实现元素垂直水平居中的几种常用方法

问题

使用 CSS 实现元素的垂直水平居中,要求掌握 Flex、Transform、Absolute+Margin、Table-cell 等方案。

解答

以下示例的 HTML 结构:

<div class="parent">
  <div class="child">居中内容</div>
</div>

方案一:Flexbox

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

方案二:Absolute + Transform

.parent {
  position: relative;
  height: 300px;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 向左上偏移自身宽高的一半 */
}

方案三:Absolute + Margin Auto

.parent {
  position: relative;
  height: 300px;
}

.child {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;    /* 四个方向都为 0,margin auto 自动分配 */
  width: 100px;    /* 必须设置宽高 */
  height: 100px;
}

方案四:Absolute + 负 Margin

.parent {
  position: relative;
  height: 300px;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  margin-top: -50px;  /* 向上偏移自身高度的一半 */
  margin-left: -50px; /* 向左偏移自身宽度的一半 */
}

方案五:Table-cell

.parent {
  display: table-cell;
  vertical-align: middle; /* 垂直居中 */
  text-align: center;     /* 水平居中 */
  width: 300px;
  height: 300px;
}

.child {
  display: inline-block; /* 配合 text-align 生效 */
}

方案六:Grid

.parent {
  display: grid;
  place-items: center; /* align-items 和 justify-items 的简写 */
  height: 300px;
}

关键点

  • Flexbox 是最简洁的方案,兼容性好,推荐优先使用
  • Transform 不需要知道子元素尺寸,适用于未知宽高的情况
  • Absolute + Margin Auto 需要子元素有固定宽高
  • 负 Margin 需要手动计算偏移量,维护成本高
  • Table-cell 是老方案,现代项目中较少使用
  • Gridplace-items: center 写法最简洁,但兼容性略差于 Flex