盒子居中
水平居中
方案1
.parent{ text-align: center; }
.child{ display: inline-block; }
方案2
.parent{ text-align: center; }
.child{ min-width:200px; margin:0 auto; }
垂直水平居中
基于绝对定位(固定宽高)
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
基于绝对定位(transform)
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
display:flex
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
display:table-cell
body {
display: table-cell;
vertical-align: middle;
text-align: center;
/* 固定宽高 */
width: 100vw;
height: 100vh;
}
.box{
display:inline-block;
}
JS实现
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';