结构代码如下所示:

1
2
3
<div class="parent">
<div class="child"></div>
</div>

第一种实现:(利用Flexbox弹性盒子布局)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.parent {
width: 500px;
height: 500px;
margin: 100px auto;
background: pink;
display: flex;
justify-content: center;
align-items: center;
}

.child {
width: 200px;
height: 200px;
background: blue;
}

第二种实现:(利用CSS3的 transform 属性)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.parent {
width: 500px;
height: 500px;
background: pink;
margin: 100px auto;
position: relative;
}

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