水平和垂直居中的方法

12 阅读1分钟

1.绝对定位

  • 方法1:绝对定位+ 负边距。用于已知宽高的元素
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px; /* 高度的一半的负值 */
  margin-left: -50px; /* 宽度的一半的负值 */
  width: 100px;
  height: 100px;
}
  • 方法2:绝对定位 + transform。适用于未知宽高的元素
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 向左上偏移自身宽高的50% */
}

2.grid 布局

.container {
  display: grid;
  place-items: center; /* 水平和垂直同时居中 */
   /* 分开居中 */
  justify-content: center; /* 水平居中 */
  align-content: center;   /* 垂直居中 */

}

3.flex 布局

.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;    /* 垂直居中 */
  height: 100vh;          /* 需要指定高度 */
}

4.表格布局

使用 display: table

.parent {
  display: table;
  width: 100%;
  height: 300px;
}

.child {
  display: table-cell;
  text-align: center;      /* 水平居中 */
  vertical-align: middle;  /* 垂直居中 */
}

5.文本居中

单行用line-height + text-align,多行用flex布局

.text-center {
  text-align: center;      /* 水平居中 */
  line-height: 100px;      /* 等于容器高度实现垂直居中 */
  height: 100px;
}

6.视口单位居中

.centered {
  position: fixed; /* 或 absolute */
  top: 50vh;       /* 视口高度的50% */
  left: 50vw;      /* 视口宽度的50% */
  transform: translate(-50%, -50%);
}