HTML部分代码:
<div style="width:300px;height:300px;" class="wrap">
<div style="width:100px;height:100px;" class="box"></div>
</div>
1、最优雅的方法flex
.wrap {
display: flex;
justify-content: center;
align-items: center;
}
2、借助table-cell
.wrap {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
3、margin + transform实现
.wrap {
overflow: hidden;
}
.box {
margin: 50% auto;
transform: translateY(-50%);
}
4、inline-block + vertical-align
.wrap {
text-align: center;
line-height: 300px;
}
.box {
display: inline-block;
vertical-align: middle;
}
5、absolute + 负margin
.wrap {
position: relative;
}
.box {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
6、absolute + margin:auto
.wrap {
position: relative;
}
.box {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
7、absolute + transform
.wrap {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
8、最新的方法grid
.wrap {
display: grid;
}
.box {
align-self: center;
justify-self: center;
}