《六种方法实现垂直居中》

104 阅读1分钟

让子元素实现垂直居中

html代码

<body>
    <div class="fa">
      <div class="son"></div>
    </div>
  </body>

1、flex

.fa {
  border: 3px solid red;
  height: 400px;
  width: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.son {
  width: 80px;
  height: 80px;
  background: green;
}

image.png

2、position绝对定位

.fa {
  border: 3px solid red;
  height: 400px;
  width: 400px;
  position: relative;
}

.son {
  width: 80px;
  height: 80px;
  background: green;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}

image.png

3、transform

.fa {
  border: 3px solid red;
  height: 400px;
  width: 400px;
}

.son {
  position: relative;
  width: 80px;
  height: 80px;
  background: green;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

image.png

4、table-cell

.fa {
  border: 3px solid red;
  height: 400px;
  width: 400px;
  display: table-cell;
  text-align: center; /*可删*/
  vertical-align: middle;
}

.son {
  width: 80px;
  height: 80px;
  background: green;
}

image.png

5、padding

.fa {
  border: 3px solid red;
  width: 400px;
  padding: 200px 0 200px 0;
}

.son {
  width: 80px;
  height: 80px;
  background: green;
}

image.png

6、伪元素

伪元素如果没有设置content属性,伪元素是无用的。

.fa {
  width: 400px;
  height: 400px;
  border: 3px solid red;
  text-align: center;
}
.fa::before,
.fa::after {
  content: "";
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}
.son {
  width: 80px;
  height: 80px;
  background: green;
  display: inline-block;
  vertical-align: middle;
}

image.png