display: grid; place-items: "> display: grid; place-items: "> display: grid; place-items: ">
面试题库 词条目录
前端Wiki/面试题库/HTML 与 CSS/CSS 高频题

CSS 垂直水平居中方案

“垂直水平居中”是面试出场率最高的 CSS 题之一。现代答案只有一行:display: grid; place-items: center; 或 flex 的 justify-content / align-items: center,它们对行内、块级、定宽不定宽的元素统统有效。

需要懂的是传统方案,因为面试官会追问“原理”:绝对定位 + margin: auto(top/left/right/bottom 全为 0 且元素有宽高,剩余空间自动均分);绝对定位 + 负 margin(要知道自身宽高一半);绝对定位 + transform: translate(-50%, -50%)(百分比相对自身,无需知道宽高)。回答时先报现代方案,再报原理方案,层次感就出来了。

  • Flex / Grid 是首选,一行属性搞定定宽 / 不定宽
  • 定位 + transform: translate(-50%,-50%):不定宽高的经典解法
  • 行内文字看父级 line-height 与 text-align;表格用 vertical-align
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<style>
  /* 方案 1:grid 一行(推荐) */
  .grid-center { display: grid; place-items: center;
                 height: 100px; border: 1px solid #f0c33c; }
  /* 方案 2:flex */
  .flex-center { display: flex; justify-content: center; align-items: center;
                 height: 100px; border: 1px solid #d29922; }
  /* 方案 3:绝对定位 + margin:auto(需宽高) */
  .pos-auto { position: relative; height: 100px; border: 1px dashed #999; }
  .pos-auto .box { position: absolute; inset: 0;     /* 四向全 0 */
                   width: 120px; height: 40px; margin: auto; background: #ffd; }
  /* 方案 4:transform(不定宽高) */
  .pos-tf { position: relative; height: 100px; border: 1px dashed #666; }
  .pos-tf .box { position: absolute; top: 50%; left: 50%;
                 transform: translate(-50%, -50%); background: #fdf; }
</style>
</head>
<body>
  <div class="grid-center">grid 居中</div>
  <div class="flex-center">flex 居中</div>
  <div class="pos-auto"><div class="box">margin:auto</div></div>
  <div class="pos-tf"><div class="box">translate</div></div>
</body>
</html>
本节要点居中四件套:grid place-items、flex、绝对定位+margin:auto、绝对定位+translate;先报现代方案再报原理方案。
🔗 相关词条CSSCSS 特效CSS3