以下方案均基于如下布局和基础样式:
1<div id="parent">
2 <div id="children">HZFE</div>
3</div>1#parent {
2 background: red;
3 height: 600px;
4}
5
6#children {
7 background: blue;
8}适用场景:子元素宽高不固定、子元素宽高固定
1#parent {
2 display: flex;
3 justify-content: center;
4 align-items: center;
5}适用场景:子元素宽高不固定、子元素宽高固定
1#parent {
2 display: grid;
3 justify-content: center;
4 align-items: center;
5}适用场景:子元素宽高不固定、子元素宽高固定
1#children {
2 display: inline-block;
3 position: relative;
4 top: 50%;
5 left: 50%;
6 transform: translate(-50%, -50%);
7}适用场景:子元素宽高固定
1#children {
2 width: 400px;
3 height: 300px;
4 position: relative;
5 top: 50%;
6 left: 50%;
7 transform: translate(-200px, -150px);
8}适用场景:子元素宽高固定
1#children {
2 width: 400px;
3 height: 300px;
4 position: relative;
5 top: calc(50% - 150px);
6 left: calc(50% - 200px);
7}适用场景:子元素宽高不固定、子元素宽高固定
1#parent {
2 position: relative;
3}
4
5#children {
6 position: absolute;
7 top: 50%;
8 left: 50%;
9 transform: translate(-50%, -50%);
10}适用场景:子元素宽高固定
1#parent {
2 position: relative;
3}
4
5#children {
6 width: 400px;
7 height: 300px;
8 position: absolute;
9 top: 50%;
10 left: 50%;
11 transform: translate(-200px, -150px);
12}适用场景:子元素宽高固定
1#parent {
2 position: relative;
3}
4
5#children {
6 width: 400px;
7 height: 300px;
8 position: absolute;
9 top: calc(50% - 150px);
10 left: calc(50% - 200px);
11}适用场景:子元素宽高固定
1#parent {
2 position: relative;
3}
4
5#children {
6 width: 400px;
7 height: 300px;
8 position: absolute;
9 top: 50%;
10 left: 50%;
11 margin-top: -150px;
12 margin-left: -200px;
13}适用场景:子元素宽高固定
1#parent {
2 position: relative;
3}
4
5#children {
6 width: 400px;
7 height: 300px;
8 position: absolute;
9 top: 0;
10 right: 0;
11 bottom: 0;
12 left: 0;
13 margin: auto;
14}适用场景:子元素宽高不固定、子元素宽高固定
1#parent {
2 width: 800px;
3 display: table-cell;
4 text-align: center;
5 vertical-align: middle;
6}
7
8#children {
9 display: inline-block;
10}前提:父元素高度固定
适用场景:子元素宽高不固定、子元素宽高固定
1#parent {
2 line-height: 600px;
3 text-align: center;
4}
5
6#children {
7 line-height: 1.5;
8 display: inline-block;
9 vertical-align: middle;
10}