Skip to content

水平垂直居中的几种方式-案例

  • 各种主流写法(Flex、Grid、定位、transform 等)
  • 典型代码 + 适用场景 + 注意点
  • 面试可用讲解总结

一、Flex 布局居中(最推荐、最常用)

  • 现代布局首选,语义清晰。
  • 不受子元素宽高影响。
  • 可用于响应式、自适应场景。

:::demo [vanilla]

html
<html>
<div class="parent">
  <div class="child">居中内容</div>
</div>
</html>
<style>
.parent {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 200px;
  border: 1px solid #ccc;
}
.child {
  background: #4f46e5;
  color: #fff;
  padding: 10px 20px;
}
</style>

:::

二、Grid 布局居中(现代方案)

  • Grid 的 place-items: center 是最简写法。
  • 对内容多、需要多维控制(如多行多列对齐)时更优。
  • Flex 更适合一维布局,Grid 更适合二维布局。
css
.parent {
  display: grid;
  place-items: center; /* 相当于 justify-items + align-items */
  height: 200px;
  border: 1px solid #ccc;
}

三、绝对定位 + transform 居中(经典通用)

  • 经典做法,兼容性极好(IE8+)。
  • 不依赖父元素布局属性。
  • 缺点:如果子元素大小变化或需要流式布局,不够灵活。
css
.parent {
  position: relative;
  height: 200px;
  border: 1px solid #ccc;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #10b981;
  color: white;
  padding: 10px 20px;
}

四、绝对定位 + margin:auto 居中(固定宽高)

  • 子元素必须有固定宽高。
  • margin: auto 会在四个方向自动平分空白。
  • 常用于弹窗、模态框。
css
.parent {
  position: relative;
  height: 200px;
}
.child {
  position: absolute;
  top: 0; bottom: 0;
  left: 0; right: 0;
  margin: auto;
  width: 100px;
  height: 50px;
  background: #ef4444;
  color: white;
  text-align: center;
  line-height: 50px;
}

五、行内元素 + text-align + line-height(适合单行文本)

  • 仅适用于单行文字,不适合多行内容或复杂块级元素。
css
.parent {
  height: 100px;
  line-height: 100px; /* 垂直居中(仅单行文本) */
  text-align: center; /* 水平居中 */
  border: 1px solid #ccc;
}

六、table-cell 居中(旧兼容方案)

  • 兼容性非常好(IE7+)。
  • 不推荐在现代布局中使用,但面试中可以提到作为历史方案。
css
.parent {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 200px;
  width: 100%;
  border: 1px solid #ccc;
}
.child {
  display: inline-block;
  background: #3b82f6;
  color: white;
  padding: 10px 20px;
}

七、CSS Grid + minmax() + auto-fit(更灵活的居中布局)

  • place-content: center 可同时控制整个内容块在父容器中居中。
  • 适合响应式卡片、空状态页等。
css
.parent {
  display: grid;
  grid-template-columns: minmax(auto, 1fr);
  place-content: center;
  height: 200px;
  border: 1px solid #ccc;
}
.child {
  background: #f59e0b;
  padding: 10px 20px;
  color: #fff;
}

八、面试总结模板

Vue 或 React 项目里我常用 Flex 布局 来实现水平垂直居中: 父容器 display:flex; justify-content:center; align-items:center; 即可。 如果遇到老项目或需要精确控制位置,我也会用 绝对定位 + transform。 另外在现代浏览器中,CSS Grid 的 place-items:center 是最简写法。 不同方案各有优劣:

  • Flex:最通用
  • Grid:最简洁
  • transform:最兼容

Bonus:响应式+全屏居中实战案例(常用于加载页)

vue
<template>
  <div class="center-box">
    <h2>正在加载中...</h2>
  </div>
</template>

<style scoped>
.center-box {
  position: fixed;
  inset: 0; /* 等价于 top:0; right:0; bottom:0; left:0; */
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255,255,255,0.9);
  z-index: 9999;
}
</style>