1. Flexbox

使用 Flexbox 是一种非常常见且灵活的方法,可以轻松实现水平和垂直居中。

.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;      /* 垂直居中 */
  height: 100vh;            /* 使容器高度为视口高度 */
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
2. Grid

使用 CSS Grid 也可以实现垂直居中

css复制代码
.container {
  display: grid;
  place-items: center; /* 水平和垂直居中 */
  height: 100vh;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
3. 使用 position 和 transform

这种方法适用于具有固定宽度和高度的元素。

css复制代码
.container {
  position: relative;
  height: 100vh;
}

.element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
4. 使用 line-height

这种方法适用于单行文本或具有固定高度的块元素。

css复制代码
.container {
  height: 100px; /* 设定固定高度 */
  line-height: 100px; /* 与容器高度相同 */
  text-align: center; /* 水平居中 */
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
5. 使用 table-cell

使用 display: table-cell; 可以在不使用表格的情况下实现垂直居中。

css复制代码
.container {
  display: table;
  height: 100vh;
  width: 100%;
}

.element {
  display: table-cell;
  vertical-align: middle; /* 垂直居中 */
  text-align: center; /* 水平居中 */
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.