Skip to content

水平居中

使用 Flexbox 布局

.parent {
  display: flex;
  justify-content: center;
}
 
.child {
  /* 子元素内容 */
}

使用 margin:auto 方式居中

.child {
  margin: 0 auto;
  display: block;
  width: 50%;     /* 具体宽度 */
}

使用 text-align,针对inline或inline-block元素

.parent {
  text-align: center;
}
 
.child {
  display: inline-block;
}

定位+transform

.parent {
  position: relative;
}
 
.child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

定位+margin负值

.father {
  position: relative;
  width: 300px;
  height: 300px;
  border: 1px solid red;
  .son {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin-top: -50px; // 垂直居中
    margin-left: -50px; // 水平居中
    background-color: green
  }
}

定位+calc

.father {
  position: relative;
  width: 300px;
  height: 300px;
  border: 1px solid red;
  .son {
    position: absolute;
    width: 100px;
    height: 100px;
    left: calc(50% - 50px); // 水平居中
    top: calc(50% - 50px); // 垂直居中
    background-color: green;
  }
}

定位+margin

.father {
  position: relative;
  width: 300px;
  height: 300px;
  border: 1px solid red;
  .son {
    position: absolute; // 子元素水平垂直居中
    width: 100px;
    height: 100px;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: green;
  }
}

垂直居中

使用 Flexbox 布局

.parent {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}
 
.child {
  /* 子元素内容 */
}

使用绝对定位和transform

.parent {
  position: relative;
}
 
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  /* 或者用下面的 transform 属性 */
  /* transform: translate(-50%, -50%); */
}

使用 line-height (适用于单行文本)

.parent {
  height: 100px; /* 需要设定高度 */
  line-height: 100px; /* 与父元素高度相同 */
}