CSS学习笔记(一)垂直居中

<div class="div0">
    <div class="redbox"></div>
    <div class="greenbox"></div>
    <div class="bluebox"></div>
  </div>

1、line-height

.div0 {
  width: 200px;
  line-height: 150px;
  text-align: center;
  border: 1px solid black;
}
.redbox {
  display: inline-block;
  width: 30px;
  height: 30px;
  background: red;
}

2、添加伪元素

vertical-align 指兄弟元素垂直位置互相居中

.div0 {
  width: 200px;
  height: 200px;
  text-align: center;
  border: 1px solid black;
}
.redbox {
  display: inline-block;
  width: 30px;
  height: 30px;
  background: red;
  vertical-align: middle;
}
.greenbox {
  display: inline-block;
  width: 30px;
  height: 60px;
  background: green;
  vertical-align: middle;
}
.bluebox {
  display: inline-block;
  width: 30px;
  height: 120px;
  background: blue;
  vertical-align: middle;
}
.div0::after {
  content: '';
  height: 100%;
  vertical-align: middle;
}

3、calc动态计算

.div0 {
  width: 200px;
  height: 200px;
  border: 1px solid black;
}
.redbox {
  width: 30px;
  height: 30px;
  background: red;
  position: relative;
  top: calc(50% - 15px);
  float: left;
}
.greenbox {
  width: 30px;
  height: 60px;
  background: green;
  position: relative;
  top: calc(50% - 30px);
  float: left;
}
.bluebox {
  width: 30px;
  height: 120px;
  background: blue;
  position: relative;
  top: calc(50% - 60px);
  float: left;
}

4、 table-cell

.div0 {
  display: table-cell;
  width: 200px;
  height: 200px;
  border: 1px solid black;
  vertical-align: middle;
}
.redbox {
  width: 30px;
  height: 30px;
  background: red;
  display: inline-block;
}
.greenbox {
  width: 30px;
  height: 60px;
  background: green;
  display: inline-block;
}
.bluebox {
  width: 30px;
  height: 120px;
  background: blue;
  display: inline-block;
}

5、transform

.div0 {
  width: 200px;
  height: 200px;
  border: 1px solid black;
}
.redbox {
  width: 30px;
  height: 30px;
  background: red;
  float: left;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

6、绝对定位

.div0 {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  position: relative;
}
.redbox {
  width: 30px;
  height: 30px;
  background: red;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

7、flex

.div0 {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}
.redbox {
  width: 30px;
  height: 30px;
  background: red;
}
原文地址:https://www.cnblogs.com/zhoulixue/p/10834732.html