一、第一种?
使用绝对定位,这种方法需要知道box的高宽
html,
body {
height: 100%;
overflow: hidden;
}
.box {
box-sizing: border-box;
width: 100px;
height: 50px;
line-height: 48px;
text-align: center;
font-size: 16px;
border: 1px solid black;
background: lightcyan;
}
body {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -25px;
}
二、第二种?
使用绝对定位,这种方法不需要知道box的高宽,但是必须要有宽高
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
三、第三种?
使用绝对定位,这种方法不需要知道box的高宽,不需要有宽高,兼容性不好
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
四、第四种?
不基于定位,不兼容,比较适用于移动端
body{
display: flex;
justify-content: center;
align-items: center;
}
五、第五种?
获取屏幕的宽和高,box 的宽和高
let HTML = document.documentElement,
winW = HTML.clientWidth, winH = HTML.clientHeight,
boxW = box.offsetWidth, boxH = box.offsetHeight;
box.style.position = "absolute";
box,style.left = (winW - boxW) / 2 + 'px';
box,style.top= (winH - boxH) / 2 + 'px';