# 父子标签, 未知高度
水平垂直都居中
定位方式
.father{
position: relative;
padding: 100px 0;
border: 1px solid black;
}
.children{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid red;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
弹性布局方式
.father {
padding: 100px 0;
display: flex;
align-items: center;
justify-content: center;
}
1
2
3
4
5
6
2
3
4
5
6
弹性布局+margin (涉及到FFC机制)
只有定位和弹性, margin才会垂直自适应布局
.father{
padding: 100px 0;
border: 1px solid black;
display: flex;
}
.children{
border: 1px solid red;
margin: auto;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 父子标签, 已知高度
定位方式
left和top为50%, 再设置margin为负宽高一半即可
.father{
width: 500px;
height: 300px;
border: 1px solid black;
position: relative;
}
.children{
width: 150px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -75px;
margin-top: -50px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
定位+margin
margin: auto 在定位情况下可以自动计算垂直margin
.father{
width: 500px;
height: 300px;
border: 1px solid black;
position: relative;
}
.children{
width: 150px;
height: 100px;
border: 1px solid red;
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 网格布局
.father{
width: 300px;
height: 300px;
display: grid;
/*每一行/每一列所占宽度*/
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px;
/*网格区域 grid areas 在CSS中的特定命名。*/
grid-template-areas:
". . ."
". c ."
". . .";
}
.children{
grid-area: c;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
← 弹性布局