# ❓ 怎么让一个 div 水平垂直居中

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

<style>
  html,
  body {
    height: 100%;
  }
  .parent {
    height: 100%;
    position: relative;
  }
  /* 我们这里给定child宽高 */
  .parent .child {
    width: 200px;
    height: 200px;
    border: 1px solid black;
  }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# position

/* step1 相对于父容齐 无视宽高 */
.parent .child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 相对自己50% */
}

/* step2 都需要给定宽高 */
.parent .child {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* step3 都需要给定宽高 */
.parent .child {
  margin-left: -100px; /* 相对父容器 */
  margin-top: -100px; /* 相对父容器 */
  position: absolute;
  top: 50%;
  left: 50%;
  border: 1px solid black;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# flex

/* step1 child无需给定宽高 */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* step2 child无需给定宽高 */
.parent {
  display: flex;
}

.parent .child {
  margin: auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# grad

/* step1 child无需给定宽高 */
.parent {
  display: grid;
}

.parent .child {
  justify-self: center;
  align-self: center;
}

/* step2 child无需给定宽高 */
.parent {
  display: grid;
}

.parent .child {
  margin: auto;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# table-cell

/* child无需给定宽高 */
/* parent 需要给具体宽高 */
.parent {
  display: table-cell;
  width: 500px;
  height: 500px;
  text-align: center;
  vertical-align: middle;
}
.parent .child {
  display: inline-block;
}
1
2
3
4
5
6
7
8
9
10
11
12