原始代码
html部分
1 2 3
| <div class="father"> <div class="son"></div> </div>
|
css部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| body { background-color: #6ed0ff; }
.father { background-color: #be33ec; border-radius: 20px; box-shadow: 0 0 15px rgb(0, 0, 0); margin: 100px auto; width: 300px; height: 300px; }
.son { background-color: #fcff00; border-radius: 20px; box-shadow: 0 0 10px rgb(0, 0, 0); width: 100px; height: 100px; }
|
效果展示
原始效果

居中效果

实现方法
absolute + margin
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; }
|
absolute + 负margin
1 2 3 4 5 6 7 8 9 10 11
| .father { position: relative; }
.son { position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; }
|
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 + transfrom
1 2 3 4 5 6 7 8
| .father { overflow: hidden; }
.son { margin: 50% auto; transform: translateY(-50%); }
|
flex
1 2 3 4 5
| .father { display: flex; justify-content: center; align-items: center; }
|
grid
1 2 3 4 5 6 7 8
| .father { display: grid; }
.son { align-self: center; justify-self: center; }
|
table-cell
1 2 3 4 5 6 7 8 9
| .father { display: table-cell; text-align: center; vertical-align: middle; }
.son { display: inline-block; }
|
inline-block + vertical-align
1 2 3 4 5 6 7 8 9
| .father { text-align: center; line-height: 300px; }
.son { display: inline-block; vertical-align: middle; }
|