• 本文使用解结构如下:

    1
    2
    3
    4
    5
    <body>
    <section class="father">
    <div class="son"></div>
    </section>
    </body>

定位+margin:auto(不定宽高可用)

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

.son {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}

定位+transform(不定宽高可用)

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

.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

定位+margin负值

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

.son {
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}

flex/grid布局(不定宽高可用)

1
2
3
4
5
6
7
8
9
10
.father {
/* 设置为flex或grid */
display: flex;
justify-content: center;
align-items: center;
}

.son {

}

table布局

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

.son {
display: inline-block;
}