最常用的 4 种居中方法

Youky ... 2023-5-9 前端
  • CSS
Less than 1 minute

# 最常用的 4 种居中方法

<div class="container">
  <div class="item"></div>
</div>
1
2
3

# 宽高未知

# flex 布局

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
1
2
3
4
5

# top、left + transform

.container {
  position: relative;
}
.item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
1
2
3
4
5
6
7
8
9

# margin: auto

.container {
  width: 500px;
  height: 300px;
  border: 1px solid #0a3b98;
  position: relative;
}
.item {
  /* 若不设置宽高则子元素会占满父容器*/
  width: 200px;
  height: 200px;
  background: #f0a238;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 宽高已知

# top、left + 负 margin

.container {
  position: relative;
}
.item {
  top: 50%;
  left: 50%;
  margin-top: -10px;
  margin-left: -20px;
  position: absolute;
}
1
2
3
4
5
6
7
8
9
10
Last update: May 9, 2023 23:23
Contributors: Youky