回答步骤:
1. 首先说这种需求在我之前的项目中是十分常见的,刚开始我用了定位的方式,让盒子相对于父级元素进行定位代码如下:
body {
position: relative;
}
.box {
width: 100px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-left: 50px;
margin-top: 25px;
}
- 第一种方案由于要知道盒子的宽高,而有一种方案不需要知道盒子的宽高。
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
- 利用CSS3的transform特性
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(50%, 50%);
}
- 后来CSS新特性有了flex布局,我发现也能做:
body {
display: flex;
justify-content: center;
align-items: cneter;
}
- 我在看掘金的时候看到一种方法,觉得挺好玩的,就记住了
body {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.box {
display: inline-block;
}
- js方法动态设置
body.style.,left = (clientX - offX) / 2 + 'px';
body.style.top = (clientY- offY) / 2 + ‘px’;