2025好运-CSS篇-实现垂直居中的方法

145 阅读1分钟

在Web开发中,实现元素的垂直居中有多种方法,以下是常见的几种方式

Flexbox方案

<div class="container">
  <div class="centered">垂直居中内容</div>
</div>

<style>
.container {
  display: flex;
  align-items: center;  /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 300px;
  border: 1px solid #ccc;
}
</style>

Grid方案

<div class="container">
  <div class="centered">垂直居中内容</div>
</div>

<style>
.container {
  display: grid;
  place-items: center; /* 同时水平和垂直居中 */
  height: 300px;
}
</style>

绝对定位 + transform

<div class="container">
  <div class="centered">垂直居中内容</div>
</div>

<style>
.container {
  position: relative;
  height: 300px;
}
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

表格布局方案

<div class="container">
  <div class="centered">垂直居中内容</div>
</div>

<style>
.container {
  display: table;
  height: 300px;
  width: 100%;
}
.centered {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
</style>

line-height 方案

<div class="container">
  单行文本垂直居中
</div>

<style>
.container {
  height: 100px;
  line-height: 100px; /* 等于容器高度 */
  text-align: center;
}
</style>

各方案适用场景:

  • Flexbox/Grid :现代布局首选,支持复杂内容
  • 绝对定位 :需要精确定位时使用
  • 表格布局 :兼容旧浏览器
  • line-height :仅适用于单行文本