Q2:页面元素的水平垂直居中

flex

1
2
3
4
5
6
7
8
9
10
11
12
13
.parent {
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-item: center;
background: yellow;
}
.child {
width: 100px;
height: 100px;
background: red;
}

相对定位 + transform

1
2
3
4
5
6
7
8
9
10
11
12
.parent {
position: relative;
}

.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
}

相对定位 + margin: auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.parent {
position: relative;
}

.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
}

相对定位 + margin 的负值

1
2
3
4
5
6
7
8
9
10
11
12
13
.parent {
position: relative;
}

.child {
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}

table-cell

1
2
3
4
5
6
7
8
9
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}

.child {
display: inline-block;
}

grid

1
2
3
4
5
6
7
8
.parent {
display: grid;
}

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