水平垂直居中
定位
1. 百分比, 知道具体宽高
让盒子距离左上50%,然后向左上移动一半的距离
#position1 {
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -50px;
}
2. 自动,不知道具体宽高
不需要具体宽高,margin自动填充剩余的空间
#position2 {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3. transform, translate, 不需要宽高
不需要宽高,translate(-50%,-50%)元素在水平方向和垂直方向同时移动,兼容性不好
#position3 {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4. JS, 不需要知道具体宽高
获得父级和盒子元素的宽高,让盒子绝对定位,并使其距离左上位置为剩余空间的一半
let HTML = document.documentElement,
winW = HTML.clientWidth,
winH = HTML.clientHeight,
box = document.getElementById("box"),
boxW = box.offsetWidth,
boxH = box.offsetHeight;
box.style.position = "absolute";
box.style.left = (winW - boxW) / 2 + "px";
box.style.top = (winH - boxH) / 2 + "px";
flex弹性盒模型
5. flex
给父节点设置flex盒子,并让他的子元素主轴交叉轴居中,不兼容,移动端常用
body {
display: flex;
justify-content: center;
align-items: center;
}