# 居中

测试示例

<div class='parent'>
  <div class='child'></div>
</div>
1
2
3
.parent {
  width: 200px;
  height: 100px;
  background: red;
}

.child {
  width: 20px;
  height: 20px;
  background: yellow;
}
1
2
3
4
5
6
7
8
9
10
11

# 水平居中

  • 方案1
.child {
  margin: 0 auto;
}
1
2
3
  • 方案2
.parent{
  text-align:center;
}

.child{
  display:inline-block;
}
1
2
3
4
5
6
7
  • 方案3
.parent{
  position:relative;
}

.child{
  position:absolute;
  left:50%;
  transform:translateX(-50%)
}
1
2
3
4
5
6
7
8
9
  • 方案4
.parent{
  display:flex;
  justify-content:center;
}
1
2
3
4

# 垂直居中

  • 方法1
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
1
2
3
4
5
6
7
8
  • 方法2
.parent {
  display:flex;
  align-items:center;
}
1
2
3
4

# 水平垂直居中

  • 方案1
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
1
2
3
4
5
  • 方案2
.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
1
2
3
4
5
6
7
8
9