CSS中常用的垂直居中

69 阅读1分钟

1. 阅读说明

  1. CSS中有多种实现垂直居中的方式,本文罗列了我在日常工作中常用的几种方法,这些方式不仅易于理解,而且能够满足95%的使用场景。在面试中,如果你能掌握以下四种方式并进一步扩展,相信此题能够轻松拿到满分。
  2. text-align: center;line-height: xxpx;margin: 0 auto;三个属性不在做赘述

2. 四种实现方式

基本标签样式

<style>
.parent {
  width: 100%;
  height: 100px;
  background-color: yellow;
}
.child {
  width: 50px;
  height: 50px;
  background-color: red;
}
</style>

<div class="parent">
    <div class="child"></div>
</div>

2.1 absolute + 负margin (使用概率50%)

注意:此方法必须知道居中盒子child的宽度

<style>
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -100px;
}
</style>

2.2 absolute + margin: auto auto (使用概率90%)

<style>
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto auto;
}
</style>

2.3 absolute + transform: translate(-50%, -50%) (使用概率50%)

<style>
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

2.4 flex (使用概率90%)

<style>
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>