基础结构、样式
复制代码html,body {
height: 100%;
}
复制代码
一、基于定位的方法
盒子宽高已知
方法1:需要宽高进行计算
body{
position:relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
margin-top: - height/2 px;
margin-left: - width/2 px;
}
复制代码
方法2:无需计算
body{
position:relative;
}
.box {
position: absolute;
top:0;
left:0;
rigth:0;
bottom:0;
margin:auto;
}
复制代码
优点:兼容性好
缺点:对自适应/动态计算宽高的盒子不友好
盒子宽高未知(自适应、动态)
body{
position:relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%)
}
复制代码
优点:盒子宽高可固定
缺点:兼容性差( ie: 你们看我干嘛 )
二、基于flex的方法
body {
display: flex;
justify-content: center;
align-items: center;
}
复制代码
优点:不受盒子宽高影响(移动端主流)
缺点:兼容性差
三、基于JavaScript的方法
中心思想:(当前屏幕宽高-盒子宽高)/2
body{
position:relative;
}
复制代码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';
复制代码
优点:兼容性好
缺点:盒子宽高需固定(非主流)
四、基于Table Cell的方法
中心思想:其本是控制文本的水平垂直居中的
.父元素{
display:table-cell
vertical-align:middle;
text-align:center
}
复制代码
但我们可以把盒子变成文本(设置display:inline、inline-block)
body {
display: table-cell;
vertical-align: middle;
text-align: center;
/* 固定宽高 */
width: 500px;
height: 500px;
}
.box {
display: inline-block;
}
复制代码
这也是一种方法,但少用(非主流)
优点:兼容性好,不受盒子宽高限制
缺点:父元素宽高需固定,不能是百分比(非主流)